next up previous
Next: About this document ... Up: Assignment 8: The Exam Previous: Part Three: The Short

Part Four: The Long Program

Write a method called evalExpr (which stands for ``evaluate expression'') that take a String as an argument and that returns an integer. The String will be an arithmetic expression including exactly three numbers and two of the operators + and -.



For example: "1 + 2 + 3" and "99 + 98 - 317" and "13685483 - 27385 + 87654".



Your method should evaluate the expression, returning the result. For the examples above, the return values would be 6, -120 and 13745752. Here are some additional rules:

1.
You will probably want to use the valueOf method, which belongs to the Integer class, and is provided as part of the Java library. It converts Strings into the corresponding integers.
     int Integer.valueOf (String s);

You may assume that valueOf works correctly even if there are spaces before or after the number, but not if there are any other non-digit characters in the String. In other words, Integer.valueOf (" 123 ") is ok, but Integer.valueOf ("a123") is not. Your program does not have to check for illegal numbers; you may assume that the String you are given is properly-formed.

2.
You will probably also want to use the substring method from the String class. On the exam, I said that you could assume that substring works correctly as described in the book. In other words, the output of the following program should be len.

     String name = "Allen Downey";
     System.out.println (name.substring(2,4));

Unfortunately, I think you will find that the implemenation of substring in our IDE is not correct. You will have to adjust your program accordingly.

YOU DO NOT NEED TO WRITE EITHER valueOf OR substring.

3.
In order to get full credit for this question, you must decompose the problem into at least two methods. In other words, you will have to design and write one or more helper methods that will make it easier to write evalExpr. The helper method(s) should do something simple and useful. None of the helper methods should be a trivial wrapper around an existing method; as a rule of thumb, the body of the method should probably be more than one line but not more than 5 lines.

HINT: You should not give any consideration to making your solution efficient. It is much more important, for the time being, to write something correct rather than fast.

As in the previous question, you will want to write a simple main method that tests your program.


next up previous
Next: About this document ... Up: Assignment 8: The Exam Previous: Part Three: The Short
Allen B. Downey
4/2/1998