Java Scanner nextBoolean() Method
Example
Print the first boolean value that is found:
// Create a scanner object
Scanner myObj = new Scanner("The value is false");
// Skip tokens until a boolean is found
while (myObj.hasNext() && !myObj.hasNextBoolean()) {
myObj.next();
}
// If there is a boolean then print it
if (myObj.hasNextBoolean()) {
System.out.print("The boolean value is ");
System.out.println(myObj.nextBoolean());
} else {
System.out.println("No boolean found");
}
Definition and Usage
The nextBoolean()
method returns the boolean value that the next token represents. A token represents a boolean value if its value matches one of the strings "true" or "false". The match is case-insensitive, which means that values like "True" and "FALSE" also represent a boolean value.
What is a token?
A token is a sequence of characters separated from other tokens by delimiters. The default delimiter is a block of whitespace characters but it can be changed with the useDelimiter()
method.
Syntax
public boolean nextBoolean()
Technical Details
Returns: | The boolean value that the next token represents. |
---|---|
Throws: |
InputMismatchException - If the token does not represent a boolean value.NoSuchElementException - If there are no more tokens in the scanner.IllegalStateException - If the scanner has been closed.
|