简体   繁体   English

在循环中终止 Java 用户输入

[英]Terminating Java User Input While Loop

I am learning Java day 1 and I have a very simple code.我正在学习 Java 第一天,我有一个非常简单的代码。

public static void main(String[] args) {
     Scanner input = new Scanner(System.in);
     while(input.hasNext()) {
        String word = input.next();
        System.out.println(word);
    }
}

After I input any sentence, the while loop seems to not terminate.在我输入任何句子后,while 循环似乎没有终止。 How would I need to change this so that the I could break out of the loop when the sentence is all read?我需要如何更改它,以便在句子全部读完时我可以跳出循环?

The hasNext() method always checks if the Scanner has another token in its input. hasNext()方法总是检查Scanner在其输入中是否有另一个令牌。 A Scanner breaks its input into tokens using a delimiter pattern that matches whitespace by default. Scanner 使用默认匹配空格的分隔符模式将其输入分解为标记。

  • Whitespace includes not only the space character, but also tab space (\t) , line feed (\n) , and more other characters空白不仅包括空格字符,还包括制表符空格(\t) 、换行符(\n)更多其他字符

hasNext() checks the input and returns true if it has another non-whitespace character. hasNext()检查输入,如果它有另一个非空白字符,则返回 true。


Your approach is correct if you want to take input from the console continuously.如果您想连续从控制台获取输入,您的方法是正确的。 However, if you just want to have single user input(ie a sentence or list of words) it is better to read the whole input and then split it accordingly.但是,如果您只想拥有单个用户输入(即一个句子或单词列表),最好阅读整个输入,然后相应地对其进行拆分。
eg:-例如:-

String str = input.nextLine();
for(String s : str.split(" ")){
    System.out.println(s);
}

Well, a simple workaround for this would be to stop whenever you find a stop or any set of strings you would like!好吧,一个简单的解决方法是在您找到停止或任何您想要的字符串时停止!

    Scanner input = new Scanner(System.in);

    while (input.hasNext()) {
        String word = input.next();
        if (word.equals("stop")) {
            break;
        }
        System.out.println(word);
    }
    input.close();
    System.out.println("THE END!");

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

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