📅  最后修改于: 2023-12-03 15:05:05.193000             🧑  作者: Mango
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.
public boolean hasNext()
The method returns a boolean value:
true
if the scanner has another token in its input queue.false
otherwise.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.
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.
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.