Java System.in问题

发布于 2024-10-12 19:36:43 字数 623 浏览 3 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

囍笑 2024-10-19 19:36:43

这段代码是正确的,它对我有用——你确定你已经编译并运行了最新的代码吗?

e
IM STILL WORKING ok?
e
IM STILL WORKING ok?
e
IM STILL WORKING ok?
ex
IM STILL WORKING ok?
exit
EXITING

This code is correct, and it works for me -- are you sure you've got the latest code compiled and running?

e
IM STILL WORKING ok?
e
IM STILL WORKING ok?
e
IM STILL WORKING ok?
ex
IM STILL WORKING ok?
exit
EXITING
ι不睡觉的鱼゛ 2024-10-19 19:36:43

我想我知道问题是什么。立即复制它...按几次输入按钮(按钮 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文