JAVA Syllabus
QUESTIONS & ANSWERS

How to accept a single character from the keyboard by using InputStreamReader() in Java?

ou can use InputStreamReader class along with BufferedReader class to read a single character 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 character: ");
    char c;
    try {
        c = (char) br.read();
        System.out.println("You entered: " + c);
    } 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 single character. We then prompt the user to enter a character and use the read() method of the BufferedReader object to read a single character from the keyboard. Note that the read() method returns an int, so we cast it to a char to get the actual character. Finally, we print out the character that was entered.

Note that the BufferedReader class can also be used to read other types of input, such as integers, doubles, and strings.

06/03/2023, 10:45 am Read : 189 times