Java 错误消息:没有这样的元素异常?
我不确定为什么会收到以下消息:Java 错误消息:没有这样的元素异常?,java,error-handling,java.util.scanner,Java,Error Handling,Java.util.scanner,我不确定为什么会收到以下消息: Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at java.util.Scanner.next
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at assessed_practical_2.PossibleQuestionSolution.main(PossibleQuestionSolution.java:24)
以下是我的主要方法代码:
package assessed_practical_2;
//Importing Resources (Random)
import java.util.Random;
//Importing Resources (Scanner)
import java.util.Scanner;
public class PossibleQuestionSolution {
public static void main(String[] args) {
// Setting up Scanner for User Input
Scanner scanner = new Scanner(System.in);
// var declaration
int userChoice;
do{
// Invoke displaymenu
displayMenu();
// Get user Input for the menu
System.out.println("Please enter choice from menu...");
userChoice = scanner.nextInt();
// Switch statement to decide which method to invoke dependent upon user input
switch (userChoice) {
case 1:
sayUserName();
break;
case 2:
sayUserNameLoop();
break;
case 3:
generateRandomNumbers();
break;
case 4:
triangleArea();
break;
case 5:
System.out.println("Quitting Program");
break;
default:
System.out.println("Sorry didnt recognise Input");
}// Switch Statement end
}while (userChoice!=5);
System.out.println("Goodbye...");
scanner.close();
}// end of main method
非常感谢您的帮助,我想这是一个关于扫描仪的nextint行的问题,但我无法修复它 我更改了以下内容,似乎允许我的程序运行: 公共类可能方程解{
// Setting up Scanner for User Input
public static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
// var declaration
int userChoice;
do{
// Invoke displaymenu
displayMenu();
// Get user Input for the menu
System.out.println("Please enter choice from menu...");
userChoice = scanner.nextInt();
// Switch statement to decide which method to invoke dependent upon user input
switch (userChoice) {
case 1:
sayUserName();
break;
case 2:
sayUserNameLoop();
break;
case 3:
generateRandomNumbers();
break;
case 4:
triangleArea();
break;
case 5:
System.out.println("Quitting Program");
break;
default:
System.out.println("Sorry didnt recognise Input");
}// Switch Statement end
}while (userChoice!=5);
System.out.println("Goodbye...");
}// end of main method
基本上,我所做的是将扫描器更改为所有方法都可以使用的公共资源,这似乎已经解决了问题,不再出现错误异常。您应该检查nextLine或nextLine是否存在,因此您应该有类似的内容:while scanner.hasNextLine(){}或while scanner.hasNextLine(){}您没有显示可能出现此错误的确切行,我担心此代码为我编译并运行时没有错误。我们需要更多信息。