Reading from the console is something that most people learn to do in a single line or two of code in most languages. However, Java is not most languages…
Consider Python:
name = input("Please enter your name: ")
C++
String name;
cout << "Please enter your name: ";
cin >> name;
Java
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String name;
System.out.println("Please enter your name: ");
name = = br.readLine();
So what is going on with that?
System.in
So lets start with the System.in
. This is the console input stream object, just like System.out
is the output console stream object. However, we cannot just read from the input console.
This stream is automatically open, and typically takes input from the user’s keyboard. We will need to use a input stream reader to work with the console input.
This object does have some methods to allow you to read an array of bytes and perform some other pretty low level stream operations. To make life easier, we typically will pass it to something like InputStreamReader
.
InputStreamReader
This object needs in input stream, which is why we pass System.in to its constructor. Without it, we couldn’t create the stream reader.
This object provides some additional features including conversion from bytes to characters which make it easier to work with. However, the characters are mostly handled individually, so we need to buffer them to get them to work together.
That will require a buffered reader.
BufferedReader
The BufferedReader
is used to read in elements, both individually and as a string.
The BufferedReader requires input from a character stream, which is why we pass in an InputStreamReader object.
We could write out the whole thing:
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
But instead we use the anonymous objects and create a new object while passing it into another objects constructor.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
This is just a little more condensed.
We can either read in individual characters, or we can read in whole lines.
System.out.print("Enter a character (Press 'q' to quit) : ");
// read characters now
do {
chr = (char) br.read();
System.out.println(chr);
} while(chr != 'q');
System.out.println("Enter some lines of text (enter 'stop' to quit) : ");
// read string now
do {
str = br.readLine();
System.out.println(str);
} while(!str.equals("stop"));
Buffered reader can be found in other places as well, as it just requires an input character stream, it doesn’t have to be from a console.
Console Inputs in Java was originally found on Access 2 Learn
One Comment
Comments are closed.