I am writing a program to ask user to choose from a menu by inputting in console.
I am new to stackoverflow and java and playing it safe by being as specific as possible. So please excuse me if you find it verbose.
I tested the code with enter "B" at prompts, and the situation is the first iteration is fine, but when the second iteration the program does not block for input any more and give the following error messages in the console(You can find where bug generated just after the comment with asterisks):
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at MainClass.main(MainClass.java:32)
public class MainClass {
public static void main(String[] args) {
AirlineClass theAirline = AirlineClass();
boolean stopAsking = false;
while (!stopAsking){
// display the menu
String menuContent = "A. Print List of all passengers.\n"
+ "B. Print List of flights.\n"
+ "C. Add a passenger to a flight.\n"
+ "D. Remove a passenger from a flight.\n"
+ "E. Print a List of passengers on a flight.\n"
+ "F. Exit.\n"
+ "Please enter your choice: ";
System.out.println(menuContent);
//create a Scanner object for input
Scanner reader = new Scanner(System.in);
String choice = reader.next().toUpperCase();
//*********************************
// bug here
reader.close();
switch (choice) {
case "A":
break;
case "B":
System.out.println("You have chose B");
break;
case "C":
break;
case "D":
break;
case "E":
break;
case "F":
System.out.println("Program exits, bye~");
stopAsking = true;
reader.close();
break;
default:
System.out.println("Invalid input detected, please try again");
reader.close();
break;
}
}
}
After I removed the line reader.close()
the program runs just fine.
I thought one possible reasons might be :
if I do reader.close()
, then every Scanner object I created reference by the name reader
with be considered closed already.
It will really be much appreciated if anyone can help me on this. And please do point out if I made some mistakes in the way of asking question.