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