【发布时间】:2018-11-03 15:45:39
【问题描述】:
对于一个类,我必须创建一个程序,该程序有一个菜单,用户可以根据他们的选择从哪里选择它运行某些方法。我遇到的问题是在我调用我的方法之后,程序在第 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
【问题讨论】:
-
我猜你在你的一个方法中使用了 Scanner(System.in) 并在那里关闭它,这将完全关闭你的应用程序的标准输入,所以你在主循环中的扫描仪将抛出 NoSuchElementException。也许将扫描仪变量移动到类字段并在所有方法中使用相同的实例。
标签: java debugging methods void