Java Reference
In-Depth Information
LISTING 15.4
The Full Text of ConsoleInput.java
1: import java.io.*;
2:
3: public class ConsoleInput {
4: public static String readLine() {
5: StringBuffer response = new StringBuffer();
6: try {
7: BufferedInputStream buff = new
8: BufferedInputStream(System.in);
9: int in = 0;
10: char inChar;
11: do {
12: in = buff.read();
13: inChar = (char) in;
14: if ((in != -1) & (in != '\n') & (in != '\r')) {
15: response.append(inChar);
16: }
17: } while ((in != -1) & (inChar != '\n') & (in != '\r'));
18: buff.close();
19: return response.toString();
20: } catch (IOException e) {
21: System.out.println(“Exception: “ + e.getMessage());
22: return null;
23: }
24: }
25:
26: public static void main(String[] arguments) {
27: System.out.print(“\nWhat is your name? “);
28: String input = ConsoleInput.readLine();
29: System.out.println(“\nHello, “ + input);
30: }
31: }
The ConsoleInput class includes a main() method that demonstrates how it can be used.
When you compile and run it as an application, the output should resemble the follow-
ing:
What is your name? Amerigo Vespucci
Hello, Amerigo Vespucci
ConsoleInput reads user input through a buffered input stream using the stream's
read() method, which returns -1 when the end of input has been reached. This occurs
when the user presses the Enter key, a carriage return (character '\r'), or a newline (char-
acter '\n').
 
Search WWH ::




Custom Search