java - 调用方法后出现 NoSuchElement 异常
问题描述
对于一个类,我必须创建一个程序,该程序具有一个菜单,用户可以根据他们的选择从哪里选择它运行某些方法。我遇到的问题是在我调用我的方法之后,程序在第 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。
推荐阅读
- angular - 如果组件调用 Http Service 方法,则进行 Angular 单元测试:错误:
: 找不到要监视的对象 - qt - QNetworkReply::RemoteHostClosedError
- php - 在参数上检查不相等
- python-3.x - 在不使用 if 语句的情况下更改无效键的值
- javascript - JavaScript:异步函数是否创建新线程?
- c++ - How to prevent a temporary on the left hand side of the assignment operator
- python - 为什么蛇不向下移动(向下键盘)
- javascript - JavaScript/ES6:如何从一个类中返回多个迭代器?
- python - 无法在python中读取excel文件
- php - 无法从数据库调用数据 - CPanel 也无法添加或管理对 cPanel 数据库的更改