我的main方法中有一个while(choice == someVal){}
块,外面有一个int menu()
方法,每次选择后都会提示用户。第一次向用户展示菜单时,它会正确读取输入内容,但是第二次始终存在NoSuchElementException。
主要方法:
public static void main(String[] args) throws SQLException {
String user = "root";
String pass = "root123";
int choice = menu();
while(choice == 1 || choice == 2) {
SeenListManager slm = new SeenListManager();
java.sql.Connection conn = slm.CreateDbConnection(user, pass);
System.out.println();
if(choice == 1) {
slm.ListAllMedia(conn, 1);
}
else if(choice == 2) {
Scanner in = new Scanner(System.in);
//get film title
System.out.print("Enter film title:");
String title = in.nextLine();
//rating
System.out.print("Enter rating (0 to 10):");
Double rating = in.nextDouble();
in.nextLine();
//comments
System.out.print("Enter any comments: ");
String review = in.nextLine();
in.close();
System.out.println();
MediaRecord sr = new MediaRecord();
sr.setTitle(title);
sr.setRating(rating);
sr.setComments(review);
//hard coded user id.
slm.AddMediaRecord(conn, 1, sr);
System.out.println();
}
conn.close();
choice = menu();
}
}
然后是menu()方法:
private static int menu() {
System.out.println("Choose menu option. Number only.");
System.out.println();
System.out.println("1. Print all films");
System.out.println("2. Add new film to list");
System.out.println("3. Exit");
System.out.println();
System.out.print("Enter choice: ");
Scanner in = new Scanner(System.in);
int choice = in.hasNext() ? in.nextInt() : -1;
in.close();
return choice;
}
我想念什么?