Scanner hasNext() Method Java

The hasNext method in Java

With this method, we get true as an output if there is some input by the user, else, we get false as an output. This method is also very simple to be used.

Check if there is a token in its input (hasNext method)

Let’s have a look at an example for this method as well, and let’s observe the output.

package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean stores = scanner.hasNext();
System.out.println(stores);
}
}

You can have a look at the output as well, and you will notice that if we have some input, it will give true, and false otherwise.

Now, let’s move on to the next method, which is similar to the previous method, but with a little difference that we are going to check for a particular pattern. We are going to give some input pattern to it and the method will check whether or not the user input matches the pattern. Please refer to the below program to understand what are we doing here.

package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean stores = scanner.hasNext(“The.*”);
System.out.println(stores);
}
}

So, if you try to implement the above program, and give some input like “The sky is blue” or “The grass is green” or something which starts with “The”, then it will return true. Here, the asterisk symbol means that after you write “The”, it will match zero or more characters. So, if you only write “The”, and hit enter, this will produce true as an output, because it matches the pattern.

Simply the constraint is that the string should start with “The”, and then there should be zero or more characters. You can try implementing the program for different inputs and see the difference.