0

I am trying to read input in main function as well as different functions, for that, I am creating two different Scanner and it is giving me an error but if I take input only in main function and pass the value in the different function it does not gives error then, what I am missing here?. I am a beginner in java.

import java.util.Scanner;
public class abc{
    public static void fun(){
        Scanner read = new Scanner(System.in);
        int a,b,c;
        a=read.nextInt();
        b=read.nextInt();
        c=read.nextInt();
        // some code

    }
    public static void main(String[] args){
       Scanner read=new Scanner(System.in);
       int t=read.nextInt();
       while(t>0){
           fun();
           t--;
       }


    }
}
Will
  • 449
  • 5
  • 23
Anonymous
  • 3
  • 4

2 Answers2

0

Why do you just don't do like this:-

import java.util.Scanner;
public class abc{
    public static void fun(int a, int b, int c){
        Scanner read = new Scanner(System.in);
        // some code

    }
    public static void main(String[] args){
       Scanner read=new Scanner(System.in);
       int t=read.nextInt();
       Object o = new Object();
       int a, b, c;
       while(t>0){
           a=read.nextInt();
           b=read.nextInt();
           c=read.nextInt();
           ob.fun(a, b, c);
           t--;
       }


    }
}

This will probably give you no error. If you don't want to do this, you can simply declare the Scanner object in the class and not in a method and try to use it.

obnoxiousnerd
  • 570
  • 1
  • 3
  • 16
0

I do not think it correct to create two Scanner for the same System.in. Why don't use the single one:

public static void main(String[] args) {
    try (Scanner scan = new Scanner(System.in)) {
        int t = scan.nextInt();
        while (t > 0) {
            fun(scan);
            t--;
        }
    }
}

public static void fun(Scanner scan) {
    int a, b, c;
    a = scan.nextInt();
    b = scan.nextInt();
    c = scan.nextInt();
    // some code
}
oleg.cherednik
  • 12,764
  • 2
  • 17
  • 25