edit - I revised my code and replaced my original work with new code, still having similar issues
This data structures class I'm taking is my first programming course, so I'm a bit out of my element. The first project is really kicking my ass. It is to make a Reverse Polish Notation Calculator. It is more or less complete, just a lot of bugs. I have been spending hours tweaking my code but when I address one problem it unleashes another. I apologize in advance for my horrible programming skills.
public class ReversePolishStack {
class SinglyLinkList {
Node head = null;
public void push(float newData) {
Node cache = this.head;
this.head = new Node(newData, cache);
}
public float pop() {
float out = this.head.data;
head = head.next;
return out;
}
public void add(float num1, float num2) {
num1 = pop();
num2 = pop();
push(num1+num2);
}
public void sub(float num1, float num2) {
num1 = pop();
num2 = pop();
push(num2-num1);
}
public void div(float num1, float num2) {
num1 = pop();
num2 = pop();
push(num2/num1);
}
public void mult(float num1, float num2) {
num1 = pop();
num2 = pop();
push(num1*num2);
}
class Node {
public float data;
public Node next;
public Node(float data, Node next) {
this.data = data;
this.next = next;
}
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
ReversePolishStack rps = new ReversePolishStack();
SinglyLinkList sll = rps.new SinglyLinkList();
String entry;
do
{
System.out.print("Enter Expression:\n");
Scanner in = new Scanner(System.in);
entry =in.nextLine();
StringTokenizer st = new StringTokenizer(entry," ");
String s1;
int count = 0;
while (st.hasMoreElements())
{
if (entry.length()<4) {// for an error message not enough input
System.out.print("Not enough input"); break;
}
else if (count>1 && sll.head.next==null) {
System.out.print("Not enough operands"); break;
}
s1 = st.nextToken();
if((s1.equals("+") || s1.equals("-") || s1.equals("*") || s1.equals("/"))) {
if(s1.equals("+"))
sll.add(sll.head.data, sll.head.next.data);
else if(s1.equals("-"))
sll.sub(sll.head.data, sll.head.next.data);
else if(s1.equals("/")) {
if (sll.head.data==0) {
System.out.println("Division by Zero enounterd."); break;
}
sll.div(sll.head.data, sll.head.next.data);
}
else if(s1.equals("*"))
sll.mult(sll.head.data, sll.head.next.data);
else
System.out.print("Unrecognized input");break;
}
else {
sll.push(Float.parseFloat(s1));
}
count++;
}
System.out.println(sll.head.data);
sll.pop();
} while(entry.equals("0")== false); // typeing a single zero terminates
System.out.print("Thanks for using my RPN Calculator!");
}
}
I have been at this for awhile and I'm sure with every attempt at fixing a bug I also added to the convolution that is my code. Any help would be appreciated!