JAVA Syllabus
QUESTIONS & ANSWERS

How to accept an Integer value from the keyboard by using InputStreamReader() in Java?

You can use InputStreamReader class along with BufferedReader class to read an integer 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 an integer: ");
    int num;
    try {
        num = Integer.parseInt(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 an integer value. We then prompt the user to enter an integer 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 parseInt() method of the Integer class to convert the string to an integer. Finally, we print out the integer value that was entered.

Note that the BufferedReader class can also be used to read other types of input, such as doubles and strings. Additionally, you should handle exceptions when reading input from the keyboard, as shown in the example.

06/03/2023, 10:52 am Read : 267 times