University of Washington, CSE 142

Lab 5: File Processing

Except where otherwise noted, the contents of this document are Copyright 2012 Stuart Reges and Marty Stepp.

lab document created by Marty Stepp, Stuart Reges, Whitaker Brand and Hélène Martin

Basic lab instructions

Today's lab

Goals for today:

Exercise : Syntax errors

Exercise - answer

  1. line 5: nextString should be next
  2. line 9: string should be String
  3. line 9: name should not be in quotes
  4. line 10: Whitaker should be in quotes
  5. line 10: cannot compare strings with ==; must use .equals
  6. line 13: cannot call replace without specifying a string object (name)
  7. line 14: toUppercase should be toUpperCase
  8. line 14: name. should come before toUpperCase, not passed as a parameter to it
  9. line 14: must say name = to store the result of toUpperCase
  10. line 15: must say name = to store the result of substring
  11. line 16: must use parentheses () when calling length

Exercise - Corrected version

public class StringOops {
    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);
        System.out.print("Type your name: ");
        String name = console.next();
        process(name);
    }

    public static void process(String "name") {
        if (name.equals("Whitaker")) {
            System.out.println("You must be really awesome.");
        }
        name = name.replace("a", "e");
        name = name.toUpperCase();
        name = name.substring(0, 3);
        System.out.println(name + " has " + name.length() + " letters");
    }
}

Exercise : while loop mystery practice-it

Fill in the boxes at right with the output produced by each method call.

public static void mystery3(int x) {
    int y = 0;
    while (x % 2 == 0) {
        y++;
        x = x / 2;
    }
    System.out.println(x + " " + y);
}
mystery3(19);
19 0
mystery3(42);
21 1
mystery3(48);
3 4
mystery3(40);
5 3
mystery3(64);
1 6

Exercise : longestName practice-it

Write a method named longestName that reads names typed by the user and prints the longest name (the name that contains the most characters) in the format shown below. Your method should accept a console Scanner and an integer n as parameters and should then prompt for n names.

A sample execution of the call longestName(console, 4) might look like the following:

name #1? roy
name #2? DANE
name #3? sTeFaNiE
name #4? Erik
Stefanie's name is longest

Try to solve this problem in Practice-It: click on the check-mark above!

File Scanner usage

 1
 2
 3
 4
 5
 6
 7
 8
 9

import java.io.*;	// for File
import java.util.*;	// for Scanner

public class FileScannerDemo {
   public static void main(String[] args) throws FileNotFoundException {
      File f = new File("test.txt");
      Scanner input = new Scanner(f);	
   }
}	

Exercise : File Scanner declaration syntax

Which of the following choices is the correct syntax for declaring a Scanner to read the file example.txt in the current directory ?

Scanner methods

Method name Description
next() reads and returns the next token as a String
nextLine() reads and returns as a String all the characters up to the next new line (\n)
nextInt() reads and returns the next token as an int, if possible
nextDouble() reads and returns the next token as double, if possible
hasNext() returns true if there is still a token in the Scanner
hasNextLine() returns true if there is still at least one line left to be read in the Scanner
hasNextInt() returns true if the next token can be read as an int
hasNextDouble() returns true if the next token can be read as an double

Exercise -A: Tokenizing

How many tokens are in the following String? 3

welcome...to the matrix.

What are the tokens that the String breaks up into?

Exercise -B: More tokenizing

How many tokens are in the following String? 9

in fourteen-hundred 92
columbus sailed the ocean blue :)

What are the tokens that the String breaks up into?

Exercise -A: Scanner practice

The next couple problems are about a file called readme.txt that has the following contents:

6.7  This file has
several input
LINES!

   10 20

What would be the output from the following code, as it would appear on the console?

Scanner input = new Scanner(new File("readme.txt"));
System.out.println(input.next());  // 6.7
System.out.println(input.next());  // This
System.out.println(input.next());  // file

Exercise -B: Scanner practice

Input file: readme.txt

6.7  This file has
several input
LINES!

   10 20

What would be the output for the following code? If there would be an error, write error .

Scanner input = new Scanner(new File("readme.txt"));
System.out.println(input.nextDouble());  // 6.7
System.out.println(input.nextDouble());  // error

Exercise -C: Scanner practice

Input file: readme.txt

6.7  This file has
several input
LINES!

   10 20

What would be the output for the following code? If there would be an error, write error .

Scanner input = new Scanner(new File("readme.txt"));
while (!input.hasNextInt()) {
    input.next();
}
System.out.println(input.nextInt());  // 10

Exercise : Words

Exercise - answer

import java.io.*;     // for File
import java.util.*;   // for Scanner

public class Words {
    public static void main(String[] args) throws FileNotFoundException {
        int wordCount = 0;
        Scanner input = new Scanner(new File("wordinput.txt"));
        
        // your code goes here ...
        while (input.hasNext()) {
            String word = input.next();
            wordCount++;
        }
        
        System.out.println("Total words = " + wordCount);
    }
}

Exercise : runningSum practice-it

Write a static method called runningSum that accepts as a parameter a Scanner holding a sequence of real numbers and that outputs the running sum of the numbers followed by the maximum running sum. For example if the Scanner contains the following data:

3.25 4.5 -8.25 7.25 3.5 4.25 -6.5 5.25

Your method should produce the following output:

running sum = 3.25 7.75 -0.5 6.75 10.25 14.5 8.0 13.25
max sum = 14.5

Click on the check-mark above to try out your solution in Practice-it!

Exercise : frequentFlier practice-it

Write a method frequentFlier that accepts a Scanner for an input file of ticket type / mileage pairs and reports how many frequent-flier miles the person earned.

For example, given the input below, your method should return 15600 (2*5000 + 1500 + 100 + 2*2000).

firstclass  5000 coach   1500  coach
100 firstclass 2000  discount 300

Exercise : flipLines practice-it

Write a method named flipLines that accepts a Scanner for an input file and writes to the console the same file's contents with each pair of lines reversed in order. For example, if the file contains:

Twas brillig and the slithy toves
did gyre and gimble in the wabe.
All mimsey were the borogroves,
and the mome raths outgrabe.

The End

your method should produce the following output:

did gyre and gimble in the wabe.
Twas brillig and the slithy toves
and the mome raths outgrabe.
All mimsey were the borogroves,
The End

Exercise : Debug ZipCode Case Study

In this exercise we will practice the jGRASP debugger using the Case Study example from the end of Chapter 6. To download this example, follow these steps:

  1. Go to the class web page and click the "Textbook" link.
  2. Find the section labeled "Code Files" and click the "code files" link.
  3. This will bring you to a directory listing that includes an entry for each chapter. Click the link for "ch06".
  4. You want to download and save the files ZipLookup.java and zipcode.txt. Right-click the file names and choose the option to save the link in whatever folder you have been using for lab work. Make sure to save them in the same folder.
  5. Compile and run ZipLookup.java in jGRASP. You might try using your own ZIP code and a relatively small radius like 0.5 miles. The program takes a while to run because it has to search a large data file.

continued on the next slide...

Exercise - jGRASP Debugger

continued on the next slide...

Exercise - jGRASP Debugger

continued on the next slide...

Exercise - jGRASP Debugger

Clear your previous break point and set a new break point inside on the printf inside the if. Then hit the resume button that looks like a play button and fill in the table below with the values for zip, lat2, and long2.

zip lat2 long2
20045 38.896599 -77.0319
20500 38.894781 -77.036122
20501 38.89872 -77.036198
20502 38.89872 -77.036198

Exercise : allDigitsOdd practice-it

Write a method named allDigitsOdd that returns whether every digit of a positive integer is odd. Your method should return true if the number consists entirely of odd digits and false if any of its digits are even. 0, 2, 4, 6, and 8 are even digits, and 1, 3, 5, 7, 9 are odd digits.

For example, allDigitsOdd(135319) returns true but allDigitsOdd(9145293) returns false.

Hint: You can pull apart a number into its digits using / 10 and % 10.

Exercise : sameDashes practice-it

Write a method sameDashes that takes two strings as parameters and that returns whether or not they have dashes in the same places (returning true if they do and returning false otherwise). For example, below are four pairs of strings of equal length that have the same pattern of dashes. Notice that the last pair has no dashes at all.

string 1:    "hi--there-you."    "-15-389"    "criminal-plan"    "abc"
string 2:    "12--(134)-7539"    "-xy-zzy"    "(206)555-1384"    "9.8"
To be considered a match, the strings must have exactly the same number of dashes in exactly the same positions. The Strings might be of different length.

Solve this problem in Practice-It by clicking on the check-mark above.

If you finish them all...

If you finish all the exercises, try out our Practice-It web tool. It lets you solve Java problems from our Building Java Programs textbook.

You can view an exercise, type a solution, and submit it to see if you have solved it correctly.

Choose some problems from the book and try to solve them!