Você está na página 1de 6

Before examining Java's control statements, we'll make a short digression that will let you

begin writing interactive programs.

Up to this point, the sample programs have displayed information to the user, but they
haven't received information from the user. Thus, you've been using console output, but
not console (keyboard) input.

The main reason for this is that Java's input system relies upon a rather complex system of
classes, the use of which requires an understanding of various features, such as exception
handling and classes.
There's no direct parallel to the very convenient println( ) method, for example, that lets
you read various types of data entered by the user.

Frankly, Java's approach to console input isn't as easy to use as one might like. Also, most
real-world Java programs and applets will be graphical and Windows based, not console
based.

However, there's one type of console input that's easy to use: reading a character from
the keyboard.
The easiest way to read a character from the keyboard is to call System.in.read( ).
System.in is the complement to System.out. It's the input object attached to the keyboard.
The read( ) method waits until the user presses a key and then returns the result. The
character is returned as an integer, so it must be cast into a char to assign it to a char
variable. By default, console input is line buffered, so you must press ENTER before any
character that you type will be sent to your program. Here's a program that reads a
character from the keyboard:
Here is a sample run of the class
KbIn program:

In the KbIn program, notice that


main( ) begins like this:
Because System.in.read( ) is being used, the program must specify the throws
java.io.IOException clause. This line is necessary to handle input errors. It's part of Java's
exception handling mechanism.

The fact that System.in is line buffered is a source of annoyance at times. When you press
ENTER, a carriage return, line feed sequence is entered into the input stream.

Furthermore, these characters are left pending in the input buffer until you read them.
Thus, for some applications, you may need to remove them (by reading them) before the
next input operation.
Summary

In this lesson, you learned that the easiest way to read a character from the keyboard is to
call System.in.read( ). The System.in statement is the complement to System.out. It's the
input object attached to the keyboard.

You also learned that when you use System.in.read( ) you must specify the throws
java.io.IOException clause. This line is necessary to handle input errors and is part of Java's
exception handling mechanism.

Você também pode gostar