0% found this document useful (0 votes)
9 views4 pages

A Calculator in Java

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views4 pages

A Calculator in Java

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

A Calculator in Java

Loo Wen Wen

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.

Implementing the Stack


A stack is a fundamental data structure that follows the Last In, First
Out (LIFO) principle, meaning that the most recently added element is
the first to be removed. This structure is particularly useful for scenarios
such as reversing data or managing function calls 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

public StaticStack(int size) {


:
top = -1;
}

One major consideration when implementing a fixed-size stack is stack


overflow — which happens when the program tries to push an element
onto a full stack. In this case, the program should check whether the stack
pointer has reached the size limit and, if so, throw an exception or provide
an error message to prevent the addition of more elements. On the flip side,
attempting to pop from an empty stack should also trigger an error or

1
a special condition since there are no elements to remove. Proper handling
of these edge cases ensures the robustness of the stack.

public void push(int val) {


if (top == stack.length - 1) {
System.out.println("Stack overflow! Cannot push more items.");
}
:
}
public int pop() {
if (top == -1) {
System.out.println("Stack empty! No items to pop.");
return -1;
}
:
}

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.

public void push(int val) {


// check if stack is full, if so, resize it
if (top == size - 1) {
resize(size * 2); // double the size
}
stack[++top] = val; // add element and increment top
}

While growing the stack dynamically makes it flexible, there may be


situations where the stack contains fewer items than its allocated space,
wasting memory. To handle this, we can implement a mechanism to shrink
the stack size when necessary. A possible approach is to halve the stack
size when it is only one-quarter full.

public int pop() {


if (top == -1) {
:

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

You might also like