Hey! I need to program a simple arithmetic calculator. I've done the parser, infix to postfix, etc. Everything's working with no problems except that it only works with one-digit numbers. For example: 10+2 evaluates to 2 instead of 12. Here's the code of the parser:
package calculator;
public class ParsePost {
private StackX theStack;
private String input;
public ParsePost(String s) {
input = s;
}
public int doParse() {
theStack = new StackX(20);
char ch;
int j;
int num1, num2, interAns;
for (j = 0; j < input.length(); j++){
ch = input.charAt(j);
if (ch >= '0' && ch <= '9'){
theStack.push((int) (ch - '0'));
}
else{
num2 = theStack.pop();
num1 = theStack.pop();
switch (ch){
case '+':
interAns = num1 + num2;
break;
case '-':
interAns = num1 - num2;
break;
case '*':
interAns = num1 * num2;
break;
case '/':
interAns = num1 / num2;
break;
default:
interAns = 0;
}
theStack.push(interAns);
}
}
interAns = theStack.pop();
return interAns;
}
}
The program uses stack. The code is:
public class StackX {
private int maxSize;
private char[] stackArray;
private int top;
public StackX(int s){
maxSize = s;
stackArray = new char[maxSize];
top = -1;
}
public void push(char j){
stackArray[++top] = j;
}
public void push(int j) {
stackArray[++top] = (char) j;
}
public char pop(){
return stackArray[top--];
}
public char peek() {
return stackArray[top];
}
public boolean isEmpty() {
return (top == -1);
}
public boolean isFull() {
return (top == maxSize - 1);
}
public int size(){
return top + 1;
}
public char peekN(int n){
return stackArray[n];
}
public void displayStack(String s) {
System.out.print(s);
System.out.print("Stack (bottom-->top): ");
for (int j = 0; j < size(); j++) {
System.out.print(peekN(j));
System.out.print(' ');
}
System.out.println("");
}
}
Please help me!