Java.Util.Scanner的NoSuchElementException

ada*_*aam 15 java java.util.scanner

我是Java的新手,但我正在阅读Java:How to program(第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
Run Code Online (Sandbox Code Playgroud)

我收到'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:
Run Code Online (Sandbox Code Playgroud)

我知道这可能是由于源代码中的某些内容与Scanner类不兼容java.util,但在推断问题所在的方面,我真的无法做到这一点.

小智 5

NoSuchElementException 通过nextElement枚举方法抛出,以指示枚举中没有更多元素.

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 
Run Code Online (Sandbox Code Playgroud)