The hasNextBoolean() method of java.util.Scanner class returns true if the next token in this scanner's input can be interpreted as a Boolean using the nextBoolean() method. The scanner does not advance past any input.
Syntax:
Java
Java
public boolean hasNextBoolean()Parameters: The function does not accepts any parameter. Return Value: This function returns true if and only if this scanner's next token is a valid Boolean. Exceptions: The function throws IllegalStateException if this scanner is closed. Below programs illustrate the above function: Program 1:
// Java program to illustrate the
// hasNextBoolean() method of Scanner class in Java
// without parameter
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
String s = "gfg true geeks!";
// new scanner with the
// specified String Object
Scanner scanner = new Scanner(s);
// use US locale to interpret Booleans in a string
scanner.useLocale(Locale.US);
// iterate till end
while (scanner.hasNext()) {
// check if the scanner's
// next token is a Boolean with the default radix
System.out.print("" + scanner.hasNextBoolean());
// print what is scanned
System.out.print(" -> " + scanner.next() + "\n");
}
// close the scanner
scanner.close();
}
}
Output:
Program 2: Program to demonstrate exception
false -> gfg true -> true false -> geeks!
// Java program to illustrate the
// hasNextBoolean() method of Scanner class in Java
// Exception case
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
String s = "gfg 2 geeks!";
// new scanner with the
// specified String Object
Scanner scanner = new Scanner(s);
// use US locale to interpret Booleans in a string
scanner.useLocale(Locale.US);
scanner.close();
// iterate till end
while (scanner.hasNext()) {
// check if the scanner's
// next token is a Boolean with the default radix
System.out.print("" + scanner.hasNextBoolean());
// print what is scanned
System.out.print(" -> " + scanner.next() + "\n");
}
// close the scanner
scanner.close();
}
catch (IllegalStateException e) {
System.out.println("Exception: " + e);
}
}
}
Output:
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextBoolean()Exception: java.lang.IllegalStateException: Scanner closed