NoSuchElementException with Java.Util.Scanner

2022-09-02 10:27:18

我对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:

我知道这可能是由于源代码中的某些内容与 来自 的类不兼容,但是在推断问题所在方面,我真的无法进一步了解这一点。Scannerjava.util


答案 1

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 

答案 2

您应该在为变量赋值之前使用。hasNextInt()


推荐