对于一个类,我必须创建一个程序,该程序有一个菜单,用户可以根据自己的选择从菜单中选择运行某些方法。我遇到的问题是在我调用我的方法之后,程序在第 30 行抛出 NoSuchElement 异常(当我将代码粘贴在下面时,它是第 26 行,它显示了 Selection = console.nextInt()),而它应该允许用户再次从菜单中选择一个选项。有人知道为什么会发生这种情况吗?
import java.util.*;
public class PartB {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
String pinNum;
int selection = 0;
boolean pin;
System.out.print("Enter pin: ");
pinNum = console.next();
pin = check_pin(pinNum);
if (pin == false) {
System.out.print("Thank you for using the menu system. Goodbye");
}
while (selection != 4 && pin==true) {
System.out.printf("%nPlease select a number from the menu below %n1: Wage "
+ "Calculator 2: Tip Calculator 3: Grocery Discount 4: Exit %n");
selection = console.nextInt();
if (selection == 1) {
calc_wages();
} else if (selection == 2) {
calc_tip();
} else if (selection == 3) {
System.out.print("We haven't gotten this far yet");
} else if (selection == 4){
System.out.print("Thank you for using the program.");
break;
} else {
System.out.print("There is no option for what you entered. Try again");
}
selection = 0;
}
console.close();
}//main
最佳答案
if(console.hasNextInt()){
selection = console.nextInt();
}
hasNextInt() 将确保在使用 nextInt() 读取流之前有一个要从流中读取的整数。否则,如果流已经耗尽,您可能会收到 NoSuchElementException。
关于java - 调用方法后出现 NoSuchElement 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53132900/