Input Characters from the Keyboard

Download Report

Transcript Input Characters from the Keyboard

Input Characters from the Keyboard
• We have 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,
that are not discussed until later.
• There is no direct parallel to the very convenient
println() method, for example, that allows you to read
various types of data entered by the user.
Input Characters from
the Keyboard
tMyn
1
• Java’s approach to console input is not as easy to
use as one might like.
• Also, most real-world Java programs and applets will
be graphical and window based, not console based.
• However, there is one type of console input that is
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 compliment to System.out.
System.in is the input object attached to the
keyboard.
Input Characters from
the Keyboard
tMyn
2
• 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.
• 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.
Input Characters from
the Keyboard
tMyn
3
• 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.
Input Characters from
the Keyboard
tMyn
4
package inputchar;
public class Main
{
public static void main(String[] args)
throws java.io.IOException
{
char ch;
System.out.println("Input a character followed by ENTER: ");
ch=(char)System.in.read();
System.out.println("You entered "+ch);
}
}
run:
Input a character followed by ENTER:
T
You entered T
BUILD SUCCESSFUL (total time: 20 seconds)
Input Characters from
the Keyboard
tMyn
5
• 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.
Input Characters from
the Keyboard
tMyn
6