I have written a working calculator program but it will not work out negative inputs. For example, 3+2 = 5.0, but, -2+5 = Wrong type of expression (error message).
The user inputs the calculation which is called "expression". I have two stacks, one for operators and one for operands and the input is broken into tokens. I need to add a way of saying, if the first number is a negative do not add the '-' to the operator stack, and, if the number after a '(' is negative do not add '-' to the operator stack. However I cannot figure this out. Can anyone help? Thanks.
This is the main evaluation method:
Stack<Double> operandStack = new Stack<Double>();
Stack<Character> operatorStack = new Stack<Character>();
//Extract operands and operators
java.util.StringTokenizer tokens = new java.util.StringTokenizer(expression, "()*/+-", true);
while(tokens.hasMoreTokens()){
String token = tokens.nextToken().trim();
System.out.print(token.trim().charAt(0));
if(token.length() == 0)
continue;
else if(token.charAt(0) == '+' || token.charAt(0) == '-'){
//Process all operators on the top of operator stack
while(!operatorStack.isEmpty() &&
(operatorStack.peek().equals('+') ||
operatorStack.peek().equals('-') ||
operatorStack.peek().equals('*') ||
operatorStack.peek().equals('/')
)){
process(operandStack, operatorStack);
}
operatorStack.push(new Character(token.charAt(0)));
}
else if(token.charAt(0) == '*' || token.charAt(0) == '/'){
while(!operatorStack.isEmpty() &&
(operatorStack.peek().equals('*') ||
operatorStack.peek().equals('/')
)){
process(operandStack, operatorStack);
}
operatorStack.push(new Character(token.charAt(0)));
}
else if(token.trim().charAt(0) == '('){
operatorStack.push(new Character('('));
}
else if(token.trim().charAt(0) == ')'){
while(!operatorStack.peek().equals('(')){
process(operandStack, operatorStack);
}
operatorStack.pop();
}
else{
operandStack.push(new Double(token));
}
}