Java I/O How to - Read number from console








Question

We would like to know how to read number from console.

Answer

/*from   w  w w  .  jav a 2s .c om*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.text.ParseException;

public class Main {
  public static void main(String[] args) {
    System.out.println("Enter a number.");
    double numberFromConsole; 
    try {
      InputStreamReader isr = new InputStreamReader(System.in);
      BufferedReader br = new BufferedReader(isr);
      String s = br.readLine();
      DecimalFormat df = new DecimalFormat();
      Number n = df.parse(s);
      numberFromConsole = n.doubleValue();
    } catch (IOException e) {
      numberFromConsole = 0;
    } catch (ParseException e) {
      numberFromConsole = 0;
    }
    System.out.println(numberFromConsole );
  }
}

The code above generates the following result.