In Java, you can also accept input from the keyboard using the InputStreamReader
class. Here's an example:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class InputStreamReaderExample {
public static void main(String[] args) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.print("Enter a string: ");
String str = br.readLine();
System.out.println("You entered " + str);
}
}
In the above code, we create a new InputStreamReader
object that wraps the System.in
input stream. We then create a BufferedReader
object that wraps the InputStreamReader
object.
In this example, we prompt the user to enter a string. We use the readLine()
method of the BufferedReader
object to read the input as a string.
Once we have the input value, we can use it in our program as needed. In this example, we print out a message that includes the string that the user entered.
Note that we need to handle the IOException
that is thrown by the readLine()
method, which is why we have added the throws IOException
clause to the main()
method signature. Additionally, we can also close the BufferedReader
object using the close()
method to free up system resources after we are done with it.