When using Scanner
to read from standard input, the newline one enters apart from what's intended to be read is not consumed, causing trouble with subsequent inputs. This can be fixed using something like exampleScanner.nextLine()
. However I'm trying to use two different scanners as below and am not able to fix the problem. I know there are a ton of questions and answers related to this type of problem with Scanner
but I still can't seem to find an answer to my particular problem. Is my problem fixable or do I have to make do with one Scanner
? Here's some code:
import java.util.Scanner;
import java.util.NoSuchElementException;
public class ScannerTest {
public static void main(String[] args) {
char sym = ' ';
int x = 0;
/* scan for char (string) */
Scanner scanForSym = new Scanner(System.in);
System.out.print("Enter a symbol: ");
try {
sym = scanForSym.next().charAt(0);
} catch (NoSuchElementException e) {
System.err.println("Failed to read sym: "+e.getMessage());
}
scanForSym.nextLine(); // makes no diff when using different Scanner
scanForSym.close();
/* scan for int with different scanner */
Scanner scanForX = new Scanner(System.in);
System.out.print("\nEnter an integer: ");
try {
x = scanForX.nextInt();
//x = scanForSym.next(); // this works fine (comment out the close above)
} catch (NoSuchElementException e) {
System.err.println("Failed to read x: "+e.getMessage());
}
scanForX.close();
System.out.println("sym: "+sym);
System.out.println("x: "+x);
}
}
Error is associated with this line:
which closes the System.in InputStream. So then this call
throws an IOException since
scanForX
is trying to read from an already closed InputStream.Try moving
somewhere below
Although (restating from the comments) it's not clear why you want to use multiple Scanner instances when they're both associated with
System.in
.