Cristian Matthias Ambæk Cristian Matthias Ambæk - 3 months ago 10
Java Question

Java multiple switch statements - NoSuchElementException

Currently i am playing around with the switch statement, and run into a problem when i have multiple loops with switch statements.

When i exit the second switch statement (to go one up), Java throws the java.util.NoSuchElementException, and i am not quite sure why since the

switchOne = sc.nextInt();

is suppose to trigger new user input?

I am hoping someone can help me cast some light on this.
I have also tried to use the scaanner without the try-with-resources and gives the same error.

public static void main(String[] args) {

int switchOne = 0;
int switchTwo = 0;

boolean breakAdmin = false;

try(Scanner sc = new Scanner(System.in)) {

while(true) {
System.out.println("Select one of the options below");
System.out.println("1: Browse books");
System.out.println("2: Get a coffe");
System.out.println("3: See previously checkouts");
System.out.println("0: Exit");
System.out.print("Option: ");

switchOne = sc.nextInt();

switch(switchOne) {
case 0:
return;
case 1:
System.out.println("!!You choose to browse over books, woohoo!!");
break;
case 2:
System.out.println("!!Sit & relax");
break;
case 3:
System.out.println("!!Let me get that list for you");
break;
case 99:
System.out.println("We welcome you!");

try(Scanner sc2 = new Scanner(System.in)) {
while(!breakAdmin) {
System.out.println("0: exit");
System.out.println("1: something");

switchTwo = sc2.nextInt();

switch(switchTwo) {
case 0:
breakAdmin = true;
break;
case 1:
System.out.println("!!admin 1");
break;
default:
System.out.println("!!This is the default case");
break;
}
}
}
breakAdmin = false;
break;// case 99 ends
default:
System.out.println("!!This is the default case");
break;
} // switch block ends
} // while loop ends
} // try with resources ends
}

Answer

try(Scanner sc2 = new Scanner(System.in)) {

A try-with-resources construct closes the resources created within the try on exit, so it is calling sc2.close() which then closes System.in.

After this you try to read from the other sc, which tries to read from System.in. But since that has been closed it no longer has anything to read.

To fix simply remove the second try, the scanner created there does not need to be closed.

EDIT: Another potential issue is that the input stream contains a non-number (for example a newline) which does not get cleared, since it cannot interpret that as a number it will throw the stated exception. When dealing with user input it might be a good idea to just read the whole line Scanner.readLine() and transforming the input yourself, such as using Integer.parseInt(...)