2017-08-20 28 views
0

我想创建一个没有案例/中断的Java菜单,我有两个问题。 (1)当我运行带有输入的程序时,应该跳过.hasNextInt()while循环,我不得不重新输入用户数据以使程序结束。 (2).hasNextInt()while循环不能防止用户输入错误类型数据的相关错误。所以我的代码仍然是用字符串输入而不是用户在while循环中被捕获的。控制菜单在Java中没有案例/中断

public static void menu(Library library){ 

    Scanner keyboard = new Scanner(System.in); 
    int selection = 999999; 

    while(selection < 1 || selection > 5){ 

     System.out.println("1. Display all books"); 
     System.out.println("2. Add a book"); 
     System.out.println("3. Delete a book"); 
     System.out.println("4. Exit the program"); 

     selection = keyboard.nextInt(); 

     while(!keyboard.hasNextInt()){ 
      System.out.println("Re-Enter an integer value"); 
      selection = keyboard.nextInt(); 
     } 

主要只是调用菜单。

回答

0

您目前的代码已经关闭,但是错误地处理了非整数输入。考虑使用以下模式:

while (!keyboard.hasNextInt()) { 
    keyboard.next(); 
    System.out.println("Re-Enter an integer value"); 
} 

在您的循环中,如果下一个标记不是整数,您将尝试使用整数。显然,这是没有意义的,不会按预期工作。

Scanner#hasNextInt()方法会阻塞,直到它可以确定下一个标记是或者不是整数。如果不是整数,上面的while循环将会消耗下一个令牌并重复。如果扫描器确定有效整数可用,则可以使用其值。

while (selection < 1 || selection > 5) { 
    System.out.println("1. Display all books"); 
    System.out.println("2. Add a book"); 
    System.out.println("3. Delete a book"); 
    System.out.println("4. Exit the program"); 

    while (!keyboard.hasNextInt()) { 
     keyboard.next(); 
     System.out.println("Re-Enter an integer value"); 
    } 
    selection = keyboard.nextInt(); 
} 
+0

这个爆炸或需要多个输入 – samgrey

+0

@samgrey不同人的不同笔画。尝试更新的答案。 –

+0

啊,明白了,它的工作原理,谢谢蒂姆的帮助! – samgrey