QUESTIONS & ANSWERS
JAVA
How to accept a string from the keyboard by using InputStreamReader() in Java?
You can use InputStreamReader
class along with BufferedReader
class to read a string 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 string: ");
String str;
try {
str = br.readLine();
System.out.println("You entered: " + str);
} 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 string. We then prompt the user to enter a string and use the readLine()
method of the BufferedReader
object to read a string from the keyboard. Finally, we print out the string that was entered.
Note that the BufferedReader
class can also be used to read other types of input, such as integers and floating-point numbers. Additionally, you should handle exceptions when reading input from the keyboard, as shown in the example.