简体   繁体   中英

While loop won't break (JAVA)

This is the code:

Scanner reader = new Scanner(System.in);
while (true) {

    System.out.print("Type a word: ");
    String word = reader.next();

    if (word.isEmpty()) {
        break;
    } 

}

Even though I have that break; within the if statement it still runs even after I enter in a blank String. What am I missing?

Assuming "reader" is a Scanner instance, try

String word = reader.nextLine();

That way the scanner will return when you press enter with an empty string.

How do you know your string is blank? You pressed enter without typing anything? How do you know the reader didn't put the new line characters into the string causing it not to be empty? Put a print of the length of the read-in string right after you read it; you'll probably find out pretty quickly why isEmpty() returns false..

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