Your Scanner
instance wraps System.in
(stdin). When you call scanner.close()
at the end of your method, you're actually closing System.in
in addition to your scanner. Once the input stream is closed, it can't be opened again.
The solution is, of course, to share a single instance of the Scanner. I note that you're using static methods, so I will similarly use a static instance in the following example. Note how I create the scanner, then I call favNumber()
, and I only close the scanner after I finish calling favNumber()
. This allows me to call favNumber()
multiple times and share the same scanner instance.
private static Scanner scanner; // note that this is a class-level static variable.
public static void main(String[] args) throws Exception {
try {
scanner = new Scanner(System.in); // create the scanner
favNumber(); // call the method
} finally {
scanner.close(); // only close the scanner when we're completely done
}
}
public static void favNumber(){
System.out.println("Enter you favorite number: ");
int favNumber = 0;
boolean hasNextInt = scanner.hasNextInt();
if(hasNextInt){
favNumber = scanner.nextInt();
scanner.nextLine(); //reads enter character
}
System.out.println("Your favorite number is: " + favNumber);
}
An alternative solution would be to pass the scanner instance as a method parameter like this:
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in); // create the scanner
favNumber(scanner); // call the method, pass the scanner
scanner.close(); // only close the scanner when we're completely done
}
public static void favNumber(Scanner scanner){
System.out.println("Enter you favorite number: ");
int favNumber = 0;
boolean hasNextInt = scanner.hasNextInt();
if(hasNextInt){
favNumber = scanner.nextInt();
scanner.nextLine(); //reads enter character
}
System.out.println("Your favorite number is: " + favNumber);
}
You can read more about closing scanners wrapping System.in in this Q&A here: Close a Scanner linked to System.in