I have a program in Java that needs to get user input from the console at multiple points across multiple classes. I tried using a scanner in each class but when I close one scanner it closes system.in so I want to use the same scanner across the whole program. I open the scanner in the main class but how do I use the same scanner in other classes?
2 Answers
You have to inject the scanner instance to other classes through constructor. Like below:
import java.util.*;
public class Test1
{
private Scanner _scanner;
public Test1(Scanner sc)
{
_scanner = sc;
}
}
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
Test1 testObj = new Test1(sc);
}
}
Scanners anyway, knowing that it closes the standard input?