Lesson 3 | Reading from the standard input |
Objective | Use the class variable System.in. and describe an approach to reading user input. |
Java System.in Read Input
When we wrote to the standard output, we used a variable that was tied to the standard output (which is, by default, the screen). This variable was the class variable System.out
.
Similarly, when we want to read from the standard input (which is, by default, the keyboard), we use a variable tied to the standard input. This variable is the class variable System.in
.
System.in
refers to a variable that is a subclass of Java's InputStream
class.
This means we can use the methods defined by the InputStream
class (in particular, the read()
method) to read characters as the user types.
StringBuffer
StringBuffer: If you are not familiar with the StringBuffer class, it's a class that keeps track of character data. However, unlike the String class, which is read-only
(that is, once you create a String object you cannot change the characters it contains), StringBuffer is read/write. That means we can append the characters we read to the end of a StringBuffer object as we read them from the keyboard.
Here is
an example of a program that reads one character at a time
from the standard input. It adds each character read, one at a time, to an instance of class
StringBuffer
and displays the characters read at the end.
Read Standard Input - Exercise