这个错误似乎是一个非常普遍的问题。我查看了其他有关此问题的 Stack Overflow 帖子并尝试实施他们的解决方案,但我仍然遇到同样的错误。完整的错误是:
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at src.file.main(file.java:29)
我确信我缺少一些非常简单的东西,但是当我阅读我的代码时,我找不到它,逻辑似乎很好。这是我的文件:
public class file {
public static void main(String[] args) throws IOException {
int choice = 0;
Scanner myVal = new Scanner(System.in);
while(choice != 3) {
System.out.println("1. enter info \n2. print info \n3.exit");
System.out.println("Enter a choice: ");
choice = myVal.nextInt(); //Line 29
if(choice == 1) {
enterInfo();
}
else if(choice == 2) {
print();
}
else if(choice == 3) {
System.exit(0);
}
}
}
static ArrayList<newType> studInfo = new ArrayList<src.newType>();
static void enterInfo() {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the information (Program year average lastname): ");
String info = keyboard.nextLine().trim();
if(info.isEmpty()) {
System.out.println("Error, no input was made.");
keyboard.close();
return;
}
String[] tokens = info.split(" ");
int size = tokens.length;
String prgm = tokens[0];
int yr = Integer.parseInt(tokens[1]);
String lastname = tokens[3];
Double avg = Double.parseDouble(tokens[2]);
newType inf = new newType(prgm, yr, avg, lastname);
studInfo.add(inf);
System.out.println("Information added.");
keyboard.close();
return;
}
示例输入:math 5 76 Smith,此信息被添加到newType可以打印的类型数组列表中,或者可以添加另一个配置文件。
该程序编译没有错误或警告,我可以成功运行该程序。当我选择选项 1 时,我以正确的格式输入我收到information added消息的所有信息,表明这是一个成功的过程。在此消息之后,出现异常。这让我相信错误实际上并不在我的 enterInfo 函数中,正如我最初所想的那样,而是当它第二次到达第 29 行时。我不知道如何解决这个错误,有人可以帮忙吗?提前致谢!