Java Utility Library

Java Scanner - nextDouble() Method



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

Syntax

public double nextDouble()

Parameters

No parameter is required.

Return Value

Returns the double scanned from the input.

Exception

  • Throws InputMismatchException, if the next token does not match the Double 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.nextDouble() method is used to scan the next token of the input as a double.

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 double
      if(MyScan.hasNextDouble())
        System.out.println("Double value is: "+ MyScan.nextDouble());
      //if the next is not a double
      else
        System.out.println("No Double Value found: "+ MyScan.next());
    }

    //close the scanner
    MyScan.close();
  }
}

The output of the above code will be:

No Double Value found: Hello
No Double Value found: World
Double value is: 10.0
No Double Value found: +
Double value is: 20.0
No Double Value found: =
Double value is: 30.0

❮ Java.util - Scanner