问题描述
我正在尝试使用 Scanner 从键盘获取 int,但出现以下错误:
I am trying to use Scanner to get an int from the keyboard, but I getting the following error:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at TableReader.mainMenu(TableReader.java:122)
at TableReader.main(TableReader.java:76)
这就是我所拥有的.它独立于我的程序的其余部分,我不明白为什么这不起作用.如果有帮助,它会在一个在 while 循环中调用的方法中声明.
This is what I have. It is independent of the rest of my program, I don't understand why this isn't working. It is declared in a method that is being called in a while loop, if that helps.
// scan for selection
Scanner s = new Scanner(System.in);
int choice = s.nextInt(); // error occurs at this line
s.close();
我通过调试器逐步完成并将错误缩小到:
I stepped through with the debugger and narrowed the error down to:
Java 运行时环境检测到一个致命错误:SIGSEGV (0xb) 在 pc=0xb6bdc8a8,pid=5587,tid=1828186944
A fatal error has been detected by the Java Runtime Environment: SIGSEGV (0xb) at pc=0xb6bdc8a8, pid=5587, tid=1828186944
JRE 版本:7.0_07-b30Java VM:OpenJDK Server VM(23.2-b09 混合模式 linux-x86 )有问题的框架:V [libjvm.so+0x4258a8] java_lang_String::utf8_length(oopDesc*)+0x58
JRE version: 7.0_07-b30 Java VM: OpenJDK Server VM (23.2-b09 mixed mode linux-x86 ) Problematic frame: V [libjvm.so+0x4258a8] java_lang_String::utf8_length(oopDesc*)+0x58
无法写入核心转储.核心转储已被禁用.要启用核心转储,请在再次启动 Java 之前尝试ulimit -c unlimited"
Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
推荐答案
您应该使用 Scanner
类中的 hasNextXXXX()
方法来确保有一个准备好读取的整数.
You should use the hasNextXXXX()
methods from the Scanner
class to make sure that there is an integer ready to be read.
问题是您被称为 nextInt()
,它从 Scanner
对象指向的流中读取下一个整数,如果那里没有要读取的整数(即如果输入已用尽,那么您将看到 NoSuchElementException
)
The problem is you are called nextInt()
which reads the next integer from the stream that the Scanner
object points to, if there is no integer there to read (i.e. if the input is exhausted then you will see that NoSuchElementException
)
在 JavaDocs 中,nextInt()
方法将在以下条件下抛出这些异常:
From the JavaDocs, the nextInt()
method will throw these exceptions under these conditions:
- InputMismatchException - 如果下一个标记与整数不匹配正则表达式,或者超出范围
- NoSuchElementException - 如果输入用完
- IllegalStateException - 如果此扫描器已关闭
您可以使用 hasNextInt()
方法轻松解决此问题:
You can fix this easily using the hasNextInt()
method:
Scanner s = new Scanner(System.in);
int choice = 0;
if(s.hasNextInt())
{
choice = s.nextInt();
}
s.close();
这篇关于nextInt() 的扫描仪错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!