0

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?

6
  • 1
    This code does not read "sentences". Java doesn't know about sentences. It reads tokens. You need to define what a sentence means. Any word ending in a punctuation mark? Or, what you have now, but with end of file terminating input. On windows ctrl-z. Everywhere else ctrl-d. Commented Jun 5, 2022 at 0:30
  • What I meant was my code is trying to get a user input and break them into words printing them separately. So as in "sentences" I guess I meant user inputs. My code prints each word of the user input separated by spaces but does not terminate the while loop when done displaying the last "word". Commented Jun 5, 2022 at 0:37
  • @2AMCoffee It is working as you expected! I am wondering about the way you run your program! onecompiler sample Commented Jun 5, 2022 at 0:42
  • Is reading with nextLine() and splitting it a better method? Commented Jun 5, 2022 at 0:42
  • I just run it with java Main.java in terminal and I'm not sure why for me the code doesn't terminate :(. Commented Jun 5, 2022 at 0:43

2 Answers 2

1

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(i.e 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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.