IC211 Spring AY 2020

HW Java IO

Name (Last, First): ____________________________________________________ Alpha: _____________________
Describe help received: _________________________________________________________________

  1. Consider the program HW18 below, which makes use of the Mystery class and its two methods:

public void compute(Scanner sc) throws Exception;
public double result();

You can get Mystery.class with:

curl -O http://faculty.cs.usna.edu/IC211/docs/hw18/Mystery.class
Or from off the Yard:
curl -O https://www.usna.edu/Users/cs/bhawkins/IC211/docs/hw18/Mystery.class

The compute(Scanner) method keeps a running tally of a mystery computation. You can call it repeatedly, and then call result() after you're finished computing.

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

public class HW18 {
  public static void main(String[] args) {
    Reader r = new InputStreamReader(System.in);
    Scanner sc = new Scanner(r);
    Mystery myster = new Mystery();

    try {
      myster.compute(sc); // can be called multiple times to continue computation
      System.out.println(myster.result()); // only called once after all compute() calls are finished
    } catch( Exception e ) {
      System.out.println("Error " + e.getMessage());
    }
  }
}

Here are some sample runs:
~/$ java HW18
23 12 17
8 -12
2 5 8
Ctrl-D
145.91727820579104
~/$ java HW18
23 12
17 the 8
Error bad input string "the"
~/$ java HW18
12
0
18 13
34.2 89
Error bad input string "34.2"
Your job is to modify the class HW18 so that
  1. It still reads from STDIN like the examples above when normally run "java HW18"
  2. When an error message is printed, the input line number that caused the error is printed out (look at the LineNumberReader class from the Java API), and
  3. If there is one command-line argument, input will be read from a file (instead of standard in) whose name is the first command-line argument. The program will behave just as before (including the line number in the error message), except the input comes from a file.

A couple more sample runs:

~/$ java HW18 in0.txt
132.70093499716234
~/$ java HW18 in1.txt
Error on line 1: bad input string "x"
Turn In: A codeprint of your source code and a screen capture of the programming running on the examples above and on the following files given at the command line: in0.txt, in1.txt, inA.txt, inB.txt.