Home »
Java programming language
Java Scanner hasNext() Method with Example
Scanner Class hasNext() method: Here, we are going to learn about the hasNext() method of Scanner Class with its syntax and example.
Submitted by Preeti Jain, on March 26, 2020
Scanner Class hasNext() method
Syntax:
public boolean hasNext();
public boolean hasNext(Pattern patt);
public boolean hasNext(String patt);
- hasNext() method is available in java.util package.
- hasNext() method is used to check whether this Scanner has any other token exists in its input or not.
- hasNext(Pattern patt) method is used to check whether the next complete token meets the given pattern or not.
- hasNext(String patt) method is used to check whether the next complete token meets the pattern (patt) formed from the given string.
- These methods may throw an exception at the time of checking the given pattern.
IllegalStateException: This exception may throw when this Scanner is not opened.
- These are non-static methods, it is accessible with class object & if we try to access these methods with the class name then we will get an error.
Parameter(s):
-
In the first case, hasNext(),
- It does not accept any parameter.
-
In the second case, hasNext(Pattern patt),
- Pattern patt – represents the pattern to read.
-
In the second case, hasNext(String patt),
- String patt – represents this string to denotes the pattern to read.
Return value:
In all the cases, the return type of the method is boolean,
- In the first case, it returns true when this Scanner has any other token in its input exists otherwise it returns false.
- In the second and third case, it returns true when this Scanner has any other token exists meet the given pattern (patt).
Example:
// Java program is to demonstrate the example
// of hasNext() method of Scanner
import java.util.*;
import java.util.regex.*;
public class HasNext {
public static void main(String[] args) {
String str = "Java Programming! 3 * 8= 24";
// Instantiates Scanner
Scanner sc = new Scanner(str);
// By using hasNext() method is to
// check whether this object has more
// token or not
boolean status = sc.hasNext();
System.out.println("sc.hasNext(): " + status);
// By using hasNext(Pattern) method is to
// check whether the given pattern exists
// in this object or not
status = sc.hasNext(Pattern.compile("...a"));
System.out.println("sc.hasNext(Pattern.compile(...a)): " + status);
// By using hasNext(String) method is to
// check whether the given pattern exists
// formed from the given string or not
status = sc.hasNext("..0.a");
System.out.println("sc.hasNext(..0.a): " + status);
// Scanner closed
sc.close();
}
}
Output
sc.hasNext(): true
sc.hasNext(Pattern.compile(...a)): true
sc.hasNext(..0.a): false