Java Utility Library

Java Scanner - nextFloat() Method



The java.util.Scanner.nextFloat() method is used to scan the next token of the input as a float. This method will throw InputMismatchException if the next token cannot be translated into a valid float value as described below. If the translation is successful, the scanner advances past the input that matched.

Syntax

public float nextFloat()

Parameters

No parameter is required.

Return Value

Returns the float scanned from the input.

Exception

  • Throws InputMismatchException, if the next token does not match the Float regular expression, or is out of range.
  • Throws NoSuchElementException, if input is exhausted.
  • Throws IllegalStateException, if this scanner is closed.

Example:

In the example below, the java.util.Scanner.nextFloat() method is used to scan the next token of the input as a float.

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()) {
      //if the next is a float
      if(MyScan.hasNextFloat())
        System.out.println("Float value is: "+ MyScan.nextFloat());
      //if the next 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