STUDENT OUTLINE

Lesson 2 - Simple I/O


INTRODUCTION:

Input and output of program data are usually referred to as I/O. There are many different ways that a Java program can perform I/O (input and output). In this lesson, we present some very simple ways to handle text input from the keyboard and output to the console.


The key topics for this lesson are:

A. Reading Input with the Scanner Class
B. Multiple Line Stream Output Expressions
C. String Objects
D. String Input

VOCABULARY:

Scanner (Reference)
STRING


CONCATENATE

DISCUSSION:

A. Reading Input with the Scanner Class

1. Many of the console based programs from the preceding lessons have not been very useful. To change any of the data values in the program, it is necessary to change the variable initializations, recompile the program, and run it again. It would be more practical if the program could ask for new values for each type of data and then compute the desired output.

2. However, accepting user input in Java has some technical complexities. Throughout this curriculum guide, we will use a special class, called Scanner (reference), to make processing input easier and less tedious.

3. Just as the System class provides System.out for output to the console, there is an object for input, System.in, from the keyboard. Unfortunately, the System.in object does not directly support convenient methods for reading numbers and strings. The Scanner class and its methods provide convenient ways to read input from System.in.

4. To use the Scanner class, you first need to import the class from the java.util package with the statement

      import java.util.Scanner;
  

5. To use a Scanner method, you need to construct a Scanner object.

      Scanner console = new Scanner (System.in);
  
Here is a list of Scanner methods.

Method

Returns

int nextInt()

Returns the next token as an int. If the next token is not an integer, InputMismatchException is thrown.

long nextLong()

Returns the next token as a long. If the next token is not an integer, InputMismatchException is thrown.

float nextFloat()

Returns the next token as a float. If the next token is not a float or lesser data type, InputMismatchException is thrown.

double nextDouble()

Returns the next token as a double. If the next token is not a double or a lesser data type, InputMismatchException is thrown.

String next()

Finds and returns the next complete token from this scanner and returns it as a string; a token is usually ended by whitespace such as a blank or line break. If no token exists, NoSuchElementException is thrown.

String nextLine()

Returns the rest of the current line, excluding any line separator at the end.

void close()

Closes the scanner.

6. Here are some example statements:

      int num1;
      String s1, s2;

      num1 = console.nextInt( );
      s1 = console.nextLine( );
      s2 = console.nextLine( );
  
When the statement num1 = console.nextInt() is encountered, execution of the program is suspended until an appropriate value is entered on the keyboard.

7. Any whitespace (spaces, tabs, newline) will separate input values. When filling character variables, white space keystrokes are ignored as the character variables are filled. If it is desirable to fill String variables with both whitespace and non-whitespace characters, the method nextLine() is required.

      String str;
      System.out.print("Enter a sentence -->  ");
      str = console.nextLine();
  

8. When requesting data from the user via the keyboard, it is good programming practice to provide a prompt. An unintroduced input statement leaves the user hanging without a clue of what the program wants. Prompt the user.

      int number;
      System.out.print("Enter an integer -->  ");
      number = console.nextInt();
  

B.  Multiple Line Output Expressions

1. We have already used examples of multiple output statements such as:

      System.out.println("The value of sum = " + sum);
  

2. There will be occasions when the length of an output statement exceeds one line of code. This can be broken up several different ways.

      System.out.println("The sum of " + num1 + " and " + num2 +
                   " = " + (num1 + num2));  
or...
      System.out.print("The sum of " + num1 + " and " + num2);
      System.out.println( " = " + (num1 + num2));
  

3. You cannot break up a String constant and wrap it around a line. This is NOT valid:

      System.out.print("A long string constant must be broken
          up into two separate quotes.  This will NOT work.");
  
However, this will work:
      System.out.print("A long string constant must be broken"
          + "up into two separate quotes.  This will work.");
  

C.  String Objects

1. Next to numbers, strings are the most important data type that most programs use. A string is a sequence of characters such as "Hello". In Java, strings are enclosed in quotation marks, which are not themselves part of the string.

2. Java does not have an explicit string data type. Instead, the String class in the java.lang package contains class methods to create string objects and commonly used string functions. Java loads the java.lang package automatically, so no special actions are required to access the String class.

3. String objects can be constructed in two ways:

      String name = "Bob Binary";
      String anotherName = new String("Betty Binary");  
Due to the usefulness and frequency of use of strings, a shorter version without the keyword new, was developed as a short-cut way of creating a String object. This creates a String object containing the characters between quote marks, just as before. A String created in this method is called a String literal. Only Strings have a short-cut like this. All other objects are constructed by using the new operator.

4. Assignment can be used to place a different string into the variable.

      name = "Boris";
      anotherName = new String("Bessy");
  

5. The number of characters in a String is called the length of the String. For example, the length of "Hello World!" is 12. Class String has its own special length method to computer the number of characters.

  int n = name.length();  
Unlike numbers, Strings are objects. Therefore, you can call methods on Strings. In the above example, the length of the String object name is computed with the method call name.length().

6. A String of length zero, containing no characters, is called the empty String and is written as "".

7. Programmers often make one String object from two Strings with the + operator, which concatenates (connects) two or more Strings into one String. Concatenation is illustrated below.

    public class DemoStringMethods
    {
        public static void main(String[] args)
        {
            String a = new String("Any old");
            String b = " String";
            String aString = a + b; // aString is "Any old String"
   
            // Show string a
            System.out.println("a: " + a);

            // Show string b
            System.out.println("b: " + b);

            // Show the result of concatenating a and b
            System.out.println("a + b: " + aString);

            // Show the number of characters in the string
            System.out.println("length: " + aString.length());
        }
    }

      Run output:

      a: Any old
      b:  String
      a + b: Any old String
      length: 14
  

8. Notice that using Strings in the context of input and output statements is identical to using other data types.

9. The String class will be covered in depth in a later lesson. For now you will use Strings for simple input and output in programs.

D.  String Input

1. The Scanner class has two methods for reading textual input from the keyboard.

2. The next method returns a reference to a String object that has from zero to many characters typed by the user at the keyboard. A word is a sequence of printable characters separated from the next word by white space. White space is defined as blank spaces, tabs, or newline characters in the input stream. White space separates ints and doubles on input. White space also separates words on input. When input from the keyboard, next stops adding text to the String object when the first white space is encountered on the input stream from the user.

3. A nextLine method returns a reference to a String object that contains from zero to many characters entered by the user. With nextLine, the String object may contain blank spaces and tabs. The newline marker is not included. It is discarded from the input stream.

4. Input is illustrated below.

    public class DemoStringInput
    {
        public static void main(String[] args)
        {
            Scanner keyboard = new Scanner( );
            String word1, word2, restOfLine;

            // ask for input from the keyboard
            System.out.print("Enter a line: ");

            // grab the first "word"
            word1 = keyboard.next();
            // grab the second "word"
            word2 = keyboard.next();
            // read the rest of the line
            restOfLine = keyboard.nextLine();

            // output the strings
            System.out.println("word1 = " + word1);
            System.out.println("word2 = " + word2);
            System.out.println("restOfLine = " + restOfLine);
        }
    }

      Run output:

      Enter a line: Hello world! I like Java Programming!
      word1 = Hello
      word2 = world!
      restOfLine =  I like Java Programming!  

SUMMARY/ REVIEW:

The class Scanner will be used in many programs. The labs in this lesson will provide an opportunity to practice using simple I/O and formatting.



Back to Java Main Page