Homework 5: A Rational Calculator

Summary: In this assignment, you will develop a simple calculator which uses rational numbers as its primary data type.

Key Topical Goals: Java basics, Loops, Strings

Assigned: Thursday, 1 April 2004

Due: 10:00 a..m, Friday, 9 April 2004

Assignment

Before break, we started to design a rational number class. It's time to finish that class and put it to use.

Write a simple calculator that can work with rational numbers. You should write a register-based calculator with three named registers (a, b, and c) and one unnamed primary register. (A register is something in which you store a value.) Your calculator should support the following commands:

• `P` (print): Prints the value in the primary register.
• `S register` (store): Copies the value from the primary register to the named register.
• `L register` (load): Loads the value from the named register into the primary register.
• `+ register-or-rational` (add): Adds the given value to the primary register and stores the result in the primary register.
• `- register-or-rational` (subtract): Subtracts the given value from the primary register and stores the result in the primary register.
• `* register-or-rational` (multiply): Multiplies the primary register by the given value and stores the result in the primary register.
• `/ register-or-rational` (divide): Divides the primary register by the given value and stores the result in the primary register.
• `= rational` (assign): Stores the given rational in the primary register.
• `Q` (quit): Quit the program.

For example,

```% java RationalCalculator
Command: = 5
Command: P
5
Command: + 3
Command: * 5
Command: P
40
Command: S a
Command: = 5
Command: P
5
Command: / a
Command: P
1/8
Command: + 1/3
Command: P
11/24
Command: Q
```

History

Wednesday, 31 March 2004 [Samuel A. Rebelsky]

• Created.

Disclaimer: I usually create these pages on the fly, which means that I rarely proofread them and they may contain bad grammar and incorrect details. It also means that I tend to update them regularly (see the history for more details). Feel free to contact me with any suggestions for changes.

This document was generated by Siteweaver on Fri May 7 09:44:08 2004.
The source to the document was last modified on Wed Mar 31 15:35:37 2004.
This document may be found at `http://www.cs.grinnell.edu/~rebelsky/Courses/CS153/2004S/Homework/hw.05.html`.

You may wish to validate this document's HTML ; ; Check with Bobby

Samuel A. Rebelsky, rebelsky@grinnell.edu