简体   繁体   中英

Terminating Java User Input While Loop

I am learning Java day 1 and I have a very simple code.

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. 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. A Scanner breaks its input into tokens using a delimiter pattern that matches whitespace by default.

  • Whitespace includes not only the space character, but also tab space (\t) , line feed (\n) , and more other characters

hasNext() checks the input and returns true if it has another non-whitespace character.


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!");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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