Problem in Calculator implementation using Stack
I have build code for simple calculator but it don't accept more than 1 operand i.e.(22 not acceptable but 2 is acceptable), the code works only with parenthesis..
here is my code
Code:
import java.util.Stack;
public static void main(String[] args) {
char []a={'(','2','+','6',')'};
System.out.println (evaluteExpression(a,5));
}
public static String evaluteExpression(char[]expression,int length){
ArrayStack operator=new ArrayStack();
Stack operand=new Stack();
int op1value = 0,op2value = 0,finalresult = 0;
char op = 0;
int result;
String op1,op2,resulttext="0";
result=0;
for(int i=0;i<length;i++){
char c=expression[i];
if(c!='('&&c!='+'&&c!='-'&&c!='*'&&c!='/'&&c!=')'&&c!='c'&&c!='s'&&c!='t')
{
String b=String.valueOf(expression[i]);
b=String.valueOf(expression[i]);
operand.push(b);
}
else
{
switch (c){
case '(': case ' ':
break;
case '-': case'+': case'*': case'/':
operator.push(c);
break;
case'c':case's':case't':
operator.push(c);
i=i+2;
break;
case ')':
op=operator.pop();
op1= (String) operand.pop();
op1value=Integer.parseInt(op1);
if(op=='+'){
op2=(String)operand.pop();
op2value=Integer.parseInt(op2);
result=op1value + op2value;
resulttext=String.valueOf(result) ;
operand.push(resulttext);
}
else if(op=='-'){
op2=(String)operand.pop();
op2value=Integer.parseInt(op2);
result=op1value-op2value;
resulttext=String.valueOf(result);
operand.push(resulttext);
}
else if(op=='*'){
op2=(String)operand.pop();
op2value=Integer.parseInt(op2);
result=op1value*op2value;
resulttext=String.valueOf(result);
operand.push(resulttext);
}
else if(op=='/'){
op2=(String)operand.pop();
op2value=Integer.parseInt(op2);
result=op2value/op1value;
resulttext=String.valueOf(result);
operand.push(resulttext);
}
else if(op=='c'){
result= (int) Math.cos(op1value);
resulttext=String.valueOf(result);
operand.push(resulttext);
}
else if(op=='s'){
op1value=Integer.parseInt(op1);
result= (int) Math.sin(op1value);
resulttext=String.valueOf(result);
operand.push(resulttext);
}
else if(op=='t'){
op1value=Integer.parseInt(op1);
result= (int) Math.tan(op1value);
resulttext=String.valueOf(result);
operand.push(resulttext);
}
}
}
}
String a=(String) operand.pop();
return a;
}
}
Code:
public interface Stack1{
public void push(char element);
public char pop();
public boolean isEmpty () ;
}
Code:
public class ArrayStack implements Stack1{
public static final int CAPACITY = 1000;
private int capacity;
private char s[];
private int top = -1;
public ArrayStack(){
this(CAPACITY);
}
public ArrayStack(int cap){
capacity = cap;
s = new char[capacity];
}
public void push(char element){
s[++top] = element;
}
public char pop(){
char elem;
elem = s[top];
s[top] = '\u0000';
-- top;
return elem;
}
public boolean isEmpty()
{
return(top < 0) ;
}
}
also if you have any better methods please help me with it..
thanks..