Re: Stack Based Calculator
Consider for a moment why this is called a stack based calculator. Perhaps a stack type data structure will be helpful. You can pop data off until you get a valid string (two operands and an operator), then push the result back onto the stack.
Re: Stack Based Calculator
Thank you for the response, I found it very useful. I decided to take a step back so I don't get to ahead of myself. I'm going to start with 2 additives only. Then attempt to solve the problem using stacks. I'm having trouble checking to see if the current item we're on is not a number (i.e: "+") but i'm having some trouble with the Code:
if stack.peek is "+"
I seem to be getting some errors. Thanks for all your help so far and thanks in advance for further explanation.
Errors:
Exception in thread "main" java.util.EmptyStackException
at java.util.Stack.peek(Unknown Source)
at Stack_Based_Calculator.main(Stack_Based_Calculator .java:19) <--- The if statement I was previously talking about.
Code:
import java.util.Stack;
public class Stack_Based_Calculator {
public static String input;
public static void main (String args[]) {
Stack stack = new Stack();
input = "5+3";
int total = 0;
for(int i = 1; i <= input.length(); i++) {
stack.push (new String(getCharacter(i)));
}
if(stack.contains("+") == true) {
for(int i = 1; i <= stack.capacity(); i++) {
if (stack.peek().toString().equalsIgnoreCase("+")) {
stack.pop();
}
else
{
total = total + Integer.parseInt((String) stack.pop());
}
}
}
System.out.println(total);
}
private static String getCharacter(int i) {
String letter = input.substring(i-1,i);
return letter;
}
}
Re: Stack Based Calculator
One of my blog entries talks about compilation and interpretation of expressions; I think it's usable here.
kind regards,
Jos