Sams Teach Yourself C in 21 Days

(singke) #1
System.out.println(“This text will be displayed on the screen.”);
System.out.println(s); // Assumes s is a String object.
Text input is a bit more complicated. Although there is a System.inobject that can be
used for keyboard input, on its own it is suitable only for single characters. To input a
line of text, which is usually what you need to do, you must use a couple of higher-level
classes called BufferedReaderandInutStreamReader. Rather than trying to explain the
details, I’ll just tell you the required steps:


  1. Import java.lang.System, java.io.InputStreamReader, and java.io.BufferedReader.

  2. Declare a variable of type BufferedReader.

  3. Initialize the variable created in step 2 as follows (assuming the variable is named
    kb):
    kb = new BufferedReader(new InputStreamReader(System.in));

  4. Call the object’s readLinemethod to input a line of text from the keyboard.
    The sample program in Listing B4.2 shows how this is done.


LISTINGB4.2 InputOutputTest.java demonstrates console I/O
1: import java.lang.System;
2: import java.io.InputStreamReader;
3: import java.io.BufferedReader;
4: import java.io.IOException;
5:
6: public class InputOutputTest {
7:
8: public static void main(String args[]) throws IOException {
9: // Set up to read lines from the keyboard.
10: BufferedReader kb;
11: String s1;
12:
13: kb = new BufferedReader(new InputStreamReader(System.in));
14: System.out.println(“Enter a line of text: “);
15: s1 = kb.readLine();
16: System.out.println(“You entered “ + s1);
17:
18: }
19: }

Enter a line of text: Java programming
You entered Java programming
Lines 1–4 of this program import the required Java classes. Line 6 defines the
classInputOutputTest, representing the test program. The throws IOException

714 Bonus Day 4

OUTPUT

ANALYSIS

39 448201x-Bonus4 8/13/02 11:19 AM Page 714

Free download pdf