📜  scanner.hasnext() - Java (1)

📅  最后修改于: 2023-12-03 15:05:05.193000             🧑  作者: Mango

Scanner.hasNext() - Java

The hasNext() method is a part of the java.util.Scanner class in java. It returns a boolean value indicating if there is another token available in the input stream or not.

Syntax
public boolean hasNext()
Return Value

The method returns a boolean value:

  • true if the scanner has another token in its input queue.
  • false otherwise.
Example
import java.util.Scanner;

public class ScannerExample {

  public static void main(String[] args) {
    Scanner scanner = new Scanner("Java is a programming language.");
    while (scanner.hasNext()) {
      System.out.println(scanner.next());
    }
  }
}

Output:

Java
is
a
programming
language.
Explanation

The above code snippet creates a new Scanner instance with a string as input. The while loop is used to iterate through all the available tokens in the input.

The hasNext() method checks if there is another token available in the input. If there is, the next() method is called to retrieve and print the token. This continues until there are no more tokens available in the input.

Conclusion

The hasNext() method in Java's Scanner class is a convenient way to check if there are any more tokens available in the input stream. It helps in writing efficient and error-free code while dealing with user inputs or reading input from files.