15-100 Lecture 12 (Febrary 13, 2008)

Java Input/Output (IO)

Today we covered Java Input/Output. Our main tool for this was a Java a Java class called a Scanner. You can find the official Java Documentation for Scanner here .

First, let's take a look at some example code and see what it does:

  // Scroll to the bottom of the lecture notes for information on this
import java.util.*;
import java.io.*;

class Input {

  public static void main (String[] args) {
   		
    // Here we declare a new Scanner called keyboard
    Scanner keyboard;

    // Here we define keyboard to be a scanner dependent on user input.
    keyboard = new Scanner(System.in);
    		
    // Declares a new String named input and sets it equal to "continue"
    String input = "continue";

    // This is a while loop which we'll look at more in a class or two
    // Basically it will run and rerun the code inside the loop until the
    // condition !input.equals("Q") is false!input.equals("Q") will become
    // false when the user inputs Q
    while (!input.equals ("Q")) {
  
      //We set the String s equal to the line of input entered by the user.  
      //We have to use (String) because it is possible that keyboard.next()
      //to return something that is not a string 

      input = (String) keyboard.next();

      // We print out the new String s
      System.out.println(input);

      // Goes back to While loop and checks to see if condition is true.
      // If true, it will run these two lines of code again.
    }

    // This lets you know when the while loop is exited
    // and is just for example purposes
    System.out.println("We left the while loop");
  }

}

If we run this code, we will be prompted to type in our user input. Then the while loop will run keyboard.next() and get the next token, using the default delimiter of " ", a.k.a. a space.

For example, the code above looks for our delimiters (spaces) and prints out the tokens before each delimiter.

If given the input, "An example sentence". It should print out:

An
example
sentence

After printing out, as above, it again prompts the user and prompts for more input, until a 'Q' is entered. For example if we input:

A B C Q

It should print out:

A
B
C
Q
We left the while loop

Adder

Here's another example, this time looking for integers.

import java.util.*;
import java.io.*;

class Input {
  public static void main (String[] args) {
 
    int total = 0;   
    int i = 0;
    
    Scanner keyboard;
    keyboard = new Scanner(System.in);
    		
    //This time, the while loop is exited when the integer i is less than 0
    while (i >= 0) {
      //sets integer i to the next integer in the input line
      i =  keyboard.nextInt();

      //adds i to total and sets it equal to total
      total = total + i;  // total += i;

      //prints out total
      System.out.println(total);
    }

    System.out.println("We exited the while loop");
  }
}

The only new information in this one should be the use of .nextInt() which gets the next integer, rather than the next string.

Let's take a look at example inputs and outputs for this one. If we provide "1 2 3" as input, it should print out:

1
3
6

If we provide an additional number as input, "10", it will print out:

16

Then, if we provide it a "-1" as input, it will terminate:

15
We exited the while loop

Note that it performed the rest of the lines of code inside the while loop before leaving, because it only checks the condition when you get to the end of the loop.

Reading From a File

This time let's try it with a file input, rather than a user input (System.in)

import java.util.*;
import java.io.*;

class Input {
  // Don't worry about the throws exception for now, just remember to type it
  // in there whenever you're dealing with Input/Output
  public static void main (String[] args) throws Exception {
 
    int total = 0;   
    int i = 0;
    
    Scanner file;

    //this will open the file (in the same directory as the program)
    // named input.txt and use that instead of user input
    file = new Scanner(new File ("input.txt"));

    //.hastNext() checks to see if there is another token
    // in the file and returns a boolean value.  Since we are
    // dealing with a file here, we can use .hasNext() because the scanner can
    // tell when the file ends whereas with System.in, only the user knows when 
    // they are going to stop sending in inputs
    while (file.hasNext()) {
      i =  file.nextInt();
      total = total + i;  // total += i;
    }
    
    System.out.println (total);
  }
}

If the input file is as follows...

1 2 3 
12
10
1 7

...it should print out:

36

Useful Tidbits

The default delimiter for Scanner class is a space, " ".

The hasNextXXXXX() methods only works for files, you cannot use them with System.in. In the case of files, the input is limited to what is contained within the file. But, in the case of System.in, the user can provide additional input at any time.

You can fake an "end of file" from the keyboard by typing "Ctrl + d"

If you request a specific type of input, e.g. an "int" via nextInt(), you will not get the carriage-return that makrs the end of the line -- it isn't part of the int. You'll need to clean it out with a subsequent next() or nextLine().

Stuff We Used But You're Not Responsible For Yet

While loops

Throws exception