QUESTIONS & ANSWERS
JAVA
How to accept a Double value from the keyboard by using InputStreamReader() in Java?
You can use InputStreamReader
class along with BufferedReader
class to read a double value from the keyboard in Java. Here's an example:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.print("Enter a double value: ");
double num;
try {
num = Double.parseDouble(br.readLine());
System.out.println("You entered: " + num);
} catch (IOException e) {
e.printStackTrace();
}
}
}
In this example, we create an InputStreamReader
object to read input from the keyboard and wrap it with a BufferedReader
object to read a double value. We then prompt the user to enter a double value and use the readLine()
method of the BufferedReader
object to read a string from the keyboard. Note that the readLine()
method returns a String
, so we use the parseDouble()
method of the Double
class to convert the string to a double value. Finally, we print out the double value that was entered.
Note that the BufferedReader
class can also be used to read other types of input, such as integers and strings. Additionally, you should handle exceptions when reading input from the keyboard, as shown in the example.