A Calculator in Java
A Calculator in Java
Fall 2024
Introduction
In this report, I will explore the implementation of a calculator that pro-
cesses mathematical expressions using reverse Polish notation (RPN).
While this may sound unfamiliar at first, RPN is a unique way of writing
mathematical expressions that can be easily handled using a stack. This re-
port will guide you through the basics of RPN, demonstrate how it simplifies
calculations, and show the practical application of stacks in programming.
A Static Stack
In this section, I will explore the implementation of a fixed size stack that
only holds integers.
The value I used for the pointer when the stack is empty is -1
1
a special condition since there are no elements to remove. Proper handling
of these edge cases ensures the robustness of the stack.
A Dynamic Stack
A dynamic stack is a stack that grows in size as more elements are pushed,
ensuring that the stack never runs out of space. To do this, we extend the
size of the stack by allocating a new larger array and copy the items from
the original array to the new array, and then continuing to push the new
item. But how much larger should this new array be? A possible approach
is to double the size of the array when it’s full, as this ensures that the
stack can handle a growing number of elements efficiently without having
to frequently resize.
2
} else {
:
if (top > 0 && top == size / 4) {
resize(size / 2); // halve the size
}
:
}
}
private void resize(int newSize) {
int[] newStack = new int[newSize];
for (int i = 0; i <= top; i++) { // copy elements from the old stack
newStack[i] = stack[i];
}
stack = newStack;
size = newSize;
}
An Abstract Class
An abstract class is a class that cannot be used to create objects and
is meant to serve as a base for other classes. It may contain abstract
methods - methods without implementation as well as concrete methods
- methods with implementation.
The goal here is to implement a stack structure using an abstract class
and extend it to handle different types of stacks: Static and Dynamic. I
was able to successfully implement the two types of stacks, amidst a few
challenges.
One of the significant design decisions was how to handle popping from
an empty stack. Initially, I considered returning a sentinel value like -1
to indicate that the stack was empty. However, since the stack was im-
plemented as a generic abstract class Stack<T> designed to handle any
object type T, it was not appropriate to return -1 as it would violate the
generic nature of the class. In fact, Java’s type system prevents returning an
int where the return type is expected to be T, causing a type mismatch.
Because of this, I shifted my approach to using a null reference when
popping from an empty stack. This worked better since null is a valid return
value for any reference type T.
public T pop() {
if (top == -1) {
System.out.println("Stack empty! No items to pop.");
return null;
}
:
3
The Calculator
To implement a calculator using a stack, there are some areas where I met
difficulties.
One of the key challenges was in handling the user input. Initially, I
treated the entire input string as a single integer, which caused a crash
when I run the file. After analysing the code, I decided to split the input
string into an array of space-separated tokens.
public static void main(String[] args) throws IOException {
:
while (run) {
:
String input = br.readLine();
String[] tokens = input.split(" ");
for (String token : tokens) {
switch (token) {
Furthermore, I challenged myself to allow for error handling in my code.
By using NumberFormatException, I was able to catch invalid inputs and
then print an error message for the user.
public static void main(String[] args) throws IOException {
:
:
for (String token : tokens) {
switch (token) {
:
default:
try {
Integer nr = Integer.parseInt(token);
stack.push(nr);
} catch (NumberFormatException e) {
System.out.println("Invalid input: " + token);
}
break;
}
}
:
Now that I have my HP-35 calculator all set up, it is time to test it.
The result of 4 2 3 * 4 + 4 * + 2 - is 42!
As mentioned, the HP-35 calculator operates using RPN. This RPN
expression of 4 2 3 * 4 + 4 * + 2 - can thus be translated into the con-
ventional infix notation of
(4 + (((2 × 3) + 4) × 4)) − 2