Java Scanner - hasNextBoolean() Method
The java.util.Scanner.hasNextBoolean() method returns true if the next token in the scanner's input can be interpreted as a boolean value using a case insensitive pattern created from the string "true|false". The scanner does not advance past any input.
Syntax
public boolean hasNextBoolean()
Parameters
No parameter is required.
Return Value
Returns true if and only if the scanner's next token is a valid boolean value.
Exception
Throws IllegalStateException, if the scanner is closed.
Example:
In the example below, the java.util.Scanner.hasNextBoolean() method is used to check whether the scanner's next token is a valid boolean value or not.
import java.util.*; public class MyClass { public static void main(String[] args) { //String to scan String MyString = "Hello World 10 == 20 returns false"; //creating a Scanner Scanner MyScan = new Scanner(MyString); while(MyScan.hasNext()) { //check if the next token is a boolean //if yes, prints boolean value if(MyScan.hasNextBoolean()) System.out.println("Boolean value is: "+ MyScan.nextBoolean()); //if the next token is not a boolean else System.out.println("No Boolean Value found: "+ MyScan.next()); } //close the scanner MyScan.close(); } }
The output of the above code will be:
No Boolean Value found: Hello No Boolean Value found: World No Boolean Value found: 10 No Boolean Value found: == No Boolean Value found: 20 No Boolean Value found: returns Boolean value is: false
❮ Java.util - Scanner