My goal is to read and print the words separately from standard input, without having to store them in an array or list.
I want this:
input: sun moon cloud
output: sun moon cloud (each word in a different line)
The following program keep waiting after printing "cloud". I don't know what the problem is
`
import java.util.Scanner;
class RandomWord{
public static void main(String[] args){
String palavra;
Scanner s = new Scanner(System.in);
while(s.hasNext()){
palavra = s.next();
System.out.println(palavra);
}
}
}
`
CodePudding user response:
You continuously reading the scanner. You have to read by scanner out of loop. For example 3 times invoking s.next(). Or create some loop end condition, for example text, "END".
If you pass all words in one line use .readLine()
CodePudding user response:
There are some similar questions, check some of theme. I think you can find answer for example here How to check the end of line using Scanner?