public static void main(String args[]){
Scanner in = new Scanner(System.in);
String a = in.next();
if (in.hasNext()) {
System.out.println("OK")
} else {
System.out.println("error");
}
}
What I want is: if the user type in a String with more than one word, print "OK". if the user type in a String with only one word, print "error".
However, it doesn't work well. When I type a single word as an input, it doesn't print "error" and I don't know why.
Your condition resolves true, if you have any kind of new input. Try something like
contains(" ")
for testing your input to contain spaces. If you want to make sure the input doesn't just contain spaces but also some other characters, usetrim()
before.hasNext() is a blocking call. Your program is going to sit around until someone types a letter, and then go to the System.out.println("OK"); line. I would recommend using an InputStreamReader passing in System.in to the constructor, and then reading the input and determining its length from there. Hope it helps.
Scanner#hasNext()
is going to return a boolean value indicatingwhether or not
there ismore input
and as long as the user has not entered
end-of-file
indicator, hasNext() is going to return truelook at this simple example to see how to use it
and the output will be something like this
Resources Learning Path: Professional Java Developer and Java™ How To Program (Early Objects), Tenth Edition
Read a line and then check whether there are more than one word.
From
Scanner#hasNext()
documentationSo in case of only one word scanner will wait for next input blocking your program.
Consider reading entire line with
nextLine()
and checking if it contains few words.You can do it same way you are doing now, but this time create Scanner based on data from line you got from user.
You can also use
line.trim().indexOf(" ") == -1
condition to determine if String doesn't contain whitespace in the middle of words.