Read number from console in Java
Description
The following code shows how to read number from console.
Example
/*w w w.j a v a 2 s . co m*/
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.