Java Reference
In-Depth Information
Reading Input from the Keyboard
You have seen and used System.out extensively throughout this topic and its labs for dis-
playing output to the console, but we have not read any input from the console yet. There
is a corresponding System.in object that represents the keyboard input from the console.
The reason I have not discussed System.in yet is because it is an InputStream, meaning that
it reads in bytes at a time. However, keyboard input is typically characters.
Therefore, to read in characters from the command prompt, you need to convert the
System.in stream from a byte stream to a reader using the InputStreamReader class. Since
keyboard input typically involves a user's entering a line of text, the BufferedReader class
can also be used to simplify processing lines of text entered by the user.
The following KeyboardInput program demonstrates how to chain together System.in,
InputStreamReader, and BufferedReader to read in lines of text from the standard console
input. Study the program and try to determine its output, which is shown in Figure 16.7.
import java.io.*;
public class KeyboardInput
{
public static void main(String [] args)
{
try
{
System.out.print(“Enter your name: “);
InputStreamReader reader =
new InputStreamReader(System.in);
BufferedReader in =
new BufferedReader(reader);
String name = in.readLine();
System.out.println(“Hello, “ + name
+ “. Enter three ints...”);
int [] values = new int[3];
double sum = 0.0;
for(int i = 0; i < values.length; i++)
{
System.out.print(“Number “ + (i+1)
+ “: “ );
String temp = in.readLine();
values[i] = Integer.parseInt(temp);
sum += values[i];
}
System.out.println(“The average equals “
+ sum/values.length);
}catch(IOException e)
{
continued
Search WWH ::




Custom Search