CS21 Week11 In-Class Exercises for Tuesday

Create a week11 subdirectory in your cs21 subdirectory, and from your week11 subdirectory, copy over my week11 files:
% cd  
% cd cs21
% mkdir week11
% cd week11
% pwd 
% cp ~newhall/public/cs21/week11/* .   

Let's first look at the Scanner Class.

The Scanner class is used to read in tokens from an input stream. A token is a sequence of characters of some form that correspond to valid values of certain Java types. For example:

  1. A sequence of non-white space alphabetic characters (which can be combined with some other optional characters like digits) correspond to a String token.
  2. A sequence of digit characters with an optional leading '-' character is an int token.
For example, the input file "infile.dat" has the following contents, and contains four String tokens and two int token:
    Hello  There   1234   
    cs21students goodbye  6556
We can read in these six tokens, by making calls to the following Scanner routines:
Scanner filein = new Scanner(new File("infile.dat"));

while (filein.hasNext()) {      // while there is another token to read
    String s = filein.next();   // reads in the String tokens "Hello" "cs21students" 
    String r = filein.next();   // reads in the String tokens "There" "goodbye"
    int x = filein.nextInt();   // reads in the int tokens 1234  6556 
    System.out.println(s + ", " + r + ", " + x);
}
Notice how the Scanner object skips over all white-space characters to the start of the next token (if we had called nextLine() instead of next() to read in the "cs21students" string after reading in the int value, then we would have returned an empty string since the '\n' character is part of a valid line token. Since '\n' is not part of a valid String token, a call to next() skips over the '\n' character after 123, and reads in the next valid String which is "cs21students".

Note that this same code sequence would work if the input file was in this crazy format:

    Hello  
    
               There   1234   cs21students 
    
    goodbye  
    
    6556