小编典典

Java.Util.Scanner的NoSuchElementException

java

我是Java的新手,但是正在阅读《 Java:如何编程》(第9版)一书,并举了一个例子,在我的一生中,我无法弄清楚问题出在哪里。

这是教科书中源代码示例的(略)增强版本:

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\n", sum ); // displays the sum on screen
  } // end method main
} // end class Addition

我收到“NoSuchElementException”错误:

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:

我知道这可能是由于源代码中的某些内容与Scannerfrom中的类不兼容所致java.util,但是在推断出问题所在的方面,我确实无法获得更多的帮助。


阅读 555

收藏
2020-03-04

共1个答案

小编典典

NoSuchElementExceptionnextElement枚举方法抛出以指示枚举中没有更多元素。

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 
2020-03-04