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?
CodePudding user response:
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);
}
CodePudding user response:
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!");