In Java, the Scanner class provides a method called hasNext() that returns true if there is another token available to be read, and false if there are no more tokens available.
Here's an example of how you can use the hasNext() method with a Scanner object:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// create a scanner object
Scanner scanner = new Scanner(System.in);
// read input until there are no more tokens
while (scanner.hasNext()) {
// read the next token
String token = scanner.next();
// do something with the token
System.out.println(token);
}
// close the scanner
scanner.close();
}
}
This code creates a Scanner object that reads from the standard input (e.g. keyboard). It then uses a while loop to read input until there are no more tokens available. Inside the loop, it reads the next token using the next() method and prints it to the console. Finally, it closes the Scanner to release any resources it is using.
The hasNext() method can be useful for reading input of unknown length, as it allows you to read tokens until there are no more available. You can also use it in combination with other methods of the Scanner class, such as nextLine(), nextInt(), etc., depending on the type of input you are expecting.
For more information about the Scanner class and its methods, you can refer to the Java documentation (https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Scanner.html).