简体   繁体   English

Java System.in问题

[英]Java System.in issue

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仍能正常工作吗?

eIM STILL WORKING ok? eIM仍能正常工作吗?

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. 我的意思是说扫描程序没有捕获单词exit的第一次出现的事实。

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

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). 立即复制它...按下输入按钮几次(按钮e),然后按下快速返回按钮(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. 对我而言,这没有多大意义,因为我认为我所做的事情不会造成任何麻烦。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM