Read Double From User in Java
beginner· Basics & I/O · I/O
Problem
Scanner.nextDouble() reads the next token from the console and parses it into a double, accepting both whole numbers and decimals.
Read a single decimal number from the console and print it.
Input
3.14
Output
You entered: 3.14
Java Program
Java
import java.util.Scanner;
public class ReadDoubleFromUser {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a decimal number: ");
double value = sc.nextDouble(); // reads and parses the typed decimal
System.out.println(value); // echo back — this compiler doesn't echo typed input itself
System.out.println("You entered: " + value);
}
}Output
Enter a decimal number: 3.14
You entered: 3.14
Core Logic
Scanner reads the typed decimal value directly, with no manual parsing needed.
How It Works
- 1
new Scanner(System.in)creates a reader attached to the console. - 2
System.out.print(...)shows a prompt without a trailing newline. - 3
sc.nextDouble()reads the next token and parses it into adouble. - 4
System.out.println(value)echoes the value right after the prompt, since most online compilers don't echo typed input themselves the way a real terminal does. - 5A separate labeled line then confirms what was read.
Typing
3.14 makes sc.nextDouble() return 3.14, printed as You entered: 3.14.💡
Key Point: nextDouble() also accepts plain integers like 7, parsing them as 7.0 — a decimal point isn't required.
Key Concepts
ScannernextDouble()console input
Approach 2: BufferedReader
Java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class ReadDoubleBufferedReader {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a decimal number: ");
// readLine() returns a String, so parse it into a double explicitly
double value = Double.parseDouble(br.readLine());
System.out.println(value); // echo back — this compiler doesn't echo typed input itself
System.out.println("You entered: " + value);
}
}
Output
Enter a decimal number: 3.14
You entered: 3.14
Core Logic
BufferedReader reads the line as raw text first, then Double.parseDouble() converts it into a double explicitly.
How It Works
- 1
new BufferedReader(new InputStreamReader(System.in))wraps standard input in a buffered character reader. - 2
br.readLine()reads the whole line as aString. - 3
Double.parseDouble(...)converts that string into adouble, sincereadLine()does no numeric parsing on its own. - 4The method signature adds
throws IOException, sincereadLine()can throw a checked exception.
Typing
3.14 gives the string "3.14", which Double.parseDouble() converts into the double 3.14.💡
Key Point: The same readLine()-then-parse pattern used for integers works here too — only the parsing method changes from Integer.parseInt() to Double.parseDouble().
Key Concepts
BufferedReaderreadLine()Double.parseDouble()