JAVA Syllabus
QUESTIONS & ANSWERS

How to accept a Float value from the keyboard by using InputStreamReader() in Java?

You can use InputStreamReader class along with BufferedReader class to read a floating-point 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 floating-point number: ");
    float num;
    try {
        num = Float.parseFloat(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 floating-point value. We then prompt the user to enter a floating-point number 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 parseFloat() method of the Float class to convert the string to a floating-point number. Finally, we print out the floating-point 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.

06/03/2023, 10:54 am Read : 173 times