Getting input from keyboard

import java.io.*;
InputStreamReader yetBufferedInput = new InputStreamReader(System.in);
BufferedReader bufferedInput = new BufferedReader(yetBufferedInput);
// Once you have created a BufferedReader, you can read either individual characters, or whole lines, from it.

try {
String inputLine = bufferedInput.readLine();

if ( inputLine != null ) {
// … process “inputLine” …
} else {
System.err.println( “No more keyboard input.” );
}
} catch ( IOException error ) {
System.err.println( “Error reading keyboard: ” + error );
}

try {
int input = bufferedInput.read();
if ( input >= 0 ) {
char c = (char) input;
// … process the input character in variable “c”
} else {
System.err.println( “No more keyboard input.” );
}
} catch( IOException error ) {
System.err.println(“Error reading keyboard:”+error );
}

readLine() can be used to read a line of text from BufferedReader, and read() reads a charactor.

try {
bufferedInput.close();
} catch ( IOException error ) {
System.err.println(“Couldn’t close the reader:” + error);
}

after that, you may close the connection to the stream and data source.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: