gpt4 book ai didi

java - NoSuchElementException 与 Java.Util.Scanner

转载 作者:太空狗 更新时间:2023-10-29 22:56:40 26 4
gpt4 key购买 nike

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

我知道这可能是由于源代码中的某些东西与 java.util 中的 Scanner 类不兼容,但我真的无法得到任何在推断问题是什么方面比这更进一步。

最佳答案

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

关于java - NoSuchElementException 与 Java.Util.Scanner,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13729294/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com