java.util.Scanner hasNextBoolean()

Description :

This java tutorial shows how to use the hasNextBoolean method of Scanner class of java.util package. This method checks if the Scanner object has boolean data type on its buffer.

Method Syntax :

public boolean hasNextBoolean()

Parameter Input :

 

DataType Parameter Description
N/A N/A N/A

 

Method Returns :

This method simply returns true if the next token string on the scanner buffer can be interpreted as boolean data type. If the Scanner object token is either “true” or “false” the Scanner returns true otherwise false.

Compatibility Version :

Requires Java 1.5 and up

Exception :

IllegalStateException

– The IllegalStateException will be thrown by this Scanner object if and only if we have invoked the method hasNextBoolean after the scanner object has been closed.

Discussion :

The method hasNextBoolean is simply to check if the token on the scanner object can be interpreted as boolean. This can be used as flag in scanning the next token of this scanner.

Java Code Example :

This java example source code demonstrates the use of hasNextBoolean method of Scanner class.

package com.teknoscope.java.tutorial.scanner;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

/*
 * Example java source code on the usage of
 * Scanner hasNextBoolean() method
 * Print the contents of a file using Scanner
 */

public class ScannerHasNextBoolean {

	public static void main(String[] args) throws FileNotFoundException {
		// Declare File object
		File file = new File("E:/tmp/java/tutorial/scanner/example.txt");
		// initialize the scanner
		Scanner scan = new Scanner(file);
		// iterate through the file line by line
		while(scan.hasNextLine()){
			// check if token consists of boolean
			if(scan.hasNextBoolean()){
				System.out.println(scan.nextLine());
			}
			else{
				scan.nextLine();
			}
		}
		scan.close();

	}
}

File Contents

************
true scanner boolean check
false check for negative logic
TRUE hasnextboolean regardless of case
************

Sample Output :

Running the hasNextBoolean() method example source code of Scanner class will give you the following output

java scanner hasnextboolean method example

java scanner hasnextboolean method example

Exception Scenario :

Exception in thread "main" java.lang.IllegalStateException: Scanner closed
	at java.util.Scanner.ensureOpen(Unknown Source)
	at java.util.Scanner.hasNext(Unknown Source)
	at java.util.Scanner.hasNextBoolean(Unknown Source)
	at com.teknoscope.java.tutorial.scanner.ScannerHasNextBoolean.main(ScannerHasNextBoolean.java:31)

Similar Method :

  • N/A

Suggested Reading List :

References :