Scanner.nextInt() 返回 java.util.NoSuchElementException
这是我的代码,它应该接受用户的输入并设置 2 个 int 值。退出函数可以正常工作,但是当输入字符串为“5 2”时,例如,它将 x 设置为 5 并在 y = s2.nextInt(); 处抛出 java.util.NoSuchElementException;行,即使有下一个 int。在我看到的 nextInt() 示例中,整数由空格分隔,扫描仪仍然拾取所有整数。我的是不是少了什么东西?
String exit = "-1";
Scanner s1 = new Scanner(System.in);
String input = s1.next();
Scanner s2 = new Scanner(input);
if (input.equals(exit))
Sequence.quit();
else {
x = s2.nextInt();
y = s2.nextInt();
}
This is my code, which is supposed to accept input from the user and set 2 int values. The exit function works correctly however when the input string is "5 2" for example, it sets x as 5 and throws the java.util.NoSuchElementException at the y = s2.nextInt(); line, even though there is a next int. In an example of nextInt() I saw, ints were seperated by a space and the scanner still picked up all the integers. Is mine missing something?
String exit = "-1";
Scanner s1 = new Scanner(System.in);
String input = s1.next();
Scanner s2 = new Scanner(input);
if (input.equals(exit))
Sequence.quit();
else {
x = s2.nextInt();
y = s2.nextInt();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果打印出变量
ìnput
,您将看到它仅包含“5” - 因为s1.next()
将停在空格处。像这样的东西:
If you print out your variable
ìnput
, you will see that it contains only "5" - sinces1.next()
wil stop at space.Something like this: