Kaaveh Mohamedi
Kaaveh Mohamedi

Reputation: 1805

.hasNext() not work correctly

    Scanner scanner = new Scanner(System.in);
    // check if the scanner has a token
    System.out.println(scanner.hasNext());

    // print the rest of the string
    System.out.println(scanner.nextLine());

    // check if the scanner has a token after printing the line
    System.out.println(scanner.hasNext());

When I run this code and enter:

Hi

print these in console:

true
Hi

but never program ended or print false.What's the problem?

Upvotes: 1

Views: 2423

Answers (2)

Logicbomb
Logicbomb

Reputation: 541

you are reading data from console that's why its does not return false value. instead of try to read data from file it sure works because when file read reach at the end of file then it will returns false because there if is no value.

Upvotes: 1

Eran
Eran

Reputation: 393986

/**
 * Returns true if this scanner has another token in its input.
 * This method may block while waiting for input to scan.
 * The scanner does not advance past any input.
 *
 * @return true if and only if this scanner has another token
 * @throws IllegalStateException if this scanner is closed
 * @see java.util.Iterator
 */
public boolean hasNext()

hasNext() blocks while waiting for input. That's why the second call to System.out.println(scanner.hasNext()); prints nothing and the program doesn't end.

If your Scanner was reading data from a file instead of from the standard input, hasNext() would have returned false when reaching the end of the file.

Upvotes: 5

Related Questions