% 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:
Hello There 1234 cs21students goodbye 6556We 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