带有 Java.Util.Scanner 的 NoSuchElementException [英] NoSuchElementException with Java.Util.Scanner
问题描述
我对 Java 非常陌生,但正在阅读《Java:如何编程》(第 9 版)这本书,并且已经找到了一个例子,我一生都无法弄清楚问题是什么.
I am very new to Java but am working through the book Java: How to program (9th ed.) and have reached an example where for the life of me I cannot figure out what the problem is.
这是教科书中源代码示例的(略微)增强版本:
Here is a (slightly) augmented version of the source code example in the textbook:
import java.util.Scanner;
public class Addition {
public static void main(String[] args) {
// creates a scanner to obtain input from a command window
Scanner input = new Scanner(System.in);
int number1; // first number to add
int number2; // second number to add
int sum; // sum of 1 & 2
System.out.print("Enter First Integer: "); // prompt
number1 = input.nextInt(); // reads first number inputted by user
System.out.print("Enter Second Integer: "); // prompt 2
number2 = input.nextInt(); // reads second number from user
sum = number1 + number2; // addition takes place, then stores the total of the two numbers in sum
System.out.printf( "Sum is %d
", sum ); // displays the sum on screen
} // end method main
} // end class Addition
我收到NoSuchElementException"错误:
I am getting the 'NoSuchElementException' error:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at Addition.main(Addition.java:16)
Enter First Integer:
我知道这可能是由于源代码中的某些内容与 java.util
中的 Scanner
类不兼容,但我真的无法得到任何在推断问题所在方面比这更进一步.
I understand that this is probably due to something in the source code that is incompatible with the Scanner
class from java.util
, but I really can't get any further than this in terms of deducing what the problem is.
推荐答案
NoSuchElementException
由枚举的 nextElement
方法抛出,表示没有更多枚举中的元素.
NoSuchElementException
Thrown by the nextElement
method of an Enumeration to indicate that there are no more elements in the enumeration.
http://docs.oracle.com/javase/7/docs/api/java/util/NoSuchElementException.html
这个怎么样:
if(input.hasNextInt() )
number1 = input.nextInt(); // if there is another number
else
number1 = 0; // nothing added in the input
这篇关于带有 Java.Util.Scanner 的 NoSuchElementException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!