IC211: Lab 6

This lab will give you some practice with files, using built-in exceptions, and creating your own exception class. You should be able to complete it in the lab.

The task is to create a simple calculator that opens a file, reads in a line of text that is a simple calculation, writes the result to another file, and repeats. The format of the file will be a separate arithmetic expression on each line. The expression will be a series of numbers and operators alternated, starting and ending with a number, like so: 4 + 3 * 2.3. Each line of the file will have a new expression.

One important item is that we have changed the rules of precedence so that it is always left to right. This makes the programming much easier, and you will have plenty of time to wrestle with techniques for handling proper precedence late. In our system, evaluation is always done left to right. So in the above example, 4 + 3 * 2.3 is 16.1, not 10.9.

  1. First, open the necessary files. Ask the user for the file names and then open those files for reading or writing. You will want a scanner for reading, and a PrintWriter for the output:
    outputStream = new PrintWriter(new BufferedWriter(new FileWriter("characteroutput.txt")));
    outputStream.println("Some Pig");
    
    You will find that some of these methods throw exceptions. You will need to catch them and deal with them gracefully, without crashing.
  2. Read in the file contents. You can use nextLine() to get a whole line, but how do you break it up into the component pieces? We can create scanners not just for input streams, but for Strings too! You can say:
    Scanner p = new Scanner("4 + 3 * 2.3");
    double num1 = p.nextDouble();
    String op = p.next();
    
    etc...
  3. You should place to code that parses the lines in it's own method.
  4. The available operators are: +, -, *, /.
  5. Now, what should be done if a line is invalid? What if it ends with an operator, or has two numbers in a row? Or maybe there's just a random word? You should throw an exception of a type that you have created. For any lines of malformed input, the output file should containt the text, Malformed Input.
  6. Show this working program to your instructor. You can use the file here.