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(){
}

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("");
}

}

It is because you enter to the stack character by character:

theStack.push((int) (ch - '0'));

Meaning that this input: 10+2, will be entered in the stack like this:
1, 0, +, 2
You want this:
10, +, 2

Try this:

String s = "10+2-3/4*11";
StringTokenizer st = new StringTokenizer(s,"[+-/*]",true);

while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}

And see what it prints.

Also for the above you will need you stack to take String array, not char:

String num2 = theStack.pop();
String num1 = theStack.pop();
if ("+".equals(operator)) {
interAns = Integer.parseInt(num1) + Integer.parseInt(num2);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.