Java System.in问题
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
if (sc.next().equals("exit")){
System.out.println("EXITING");
System.exit(0);
} else {
System.out.println("IM STILL WORKING ok?");
}
}
}
}
所以这是我前几天写的一段代码,试图找出答案(实际上并不重要)。执行这段代码的结果是:
eIM STILL WORKING ok?
eIM 还能正常工作吗?
退出
IM 还在工作吗?
exit
EXITING
有人可以解释一下为什么会发生这种情况吗?我的意思是扫描仪没有捕获单词 exit 的第一次出现。
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
if (sc.next().equals("exit")){
System.out.println("EXITING");
System.exit(0);
} else {
System.out.println("IM STILL WORKING ok?");
}
}
}
}
So here is a piece of code i was writing the other day to try and figure sth out (doesn't really matter what). The result of executing this code is :
eIM STILL WORKING ok?
eIM STILL WORKING ok?
exit
IM STILL WORKING ok?
exit
EXITING
Can somebody kindly explain why this has happened? I mean the fact the the Scanner didnt capture the first occurence of the word exit.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这段代码是正确的,它对我有用——你确定你已经编译并运行了最新的代码吗?
This code is correct, and it works for me -- are you sure you've got the latest code compiled and running?
我想我知道问题是什么。立即复制它...按几次输入按钮(按钮 e),然后按快速返回按钮(输入)。这就是为什么有些线路同时具有输入和输出的原因。之后扫描仪无法获取第一次出现的退出。这对我来说没有多大意义,因为我认为我所做的不应该造成任何麻烦。
I think i know what the problem is . reproduced it right now... pressed several time a button for input (button e) followed by a fast return button (enter). This is why some lines have both the input and output. after that Scanner is unable to get the first occurrence of exit. It doesn't make that much sense to me tho as I think what I did shouldn't cause any trouble.