在java中使用堆栈计算后缀表达式
我正试图为postfix求值编写代码,但我得到一个错误 无法将java.lang.String转换为java.lang.Integer,问题出在以下行在java中使用堆栈计算后缀表达式,java,data-structures,stack,Java,Data Structures,Stack,我正试图为postfix求值编写代码,但我得到一个错误 无法将java.lang.String转换为java.lang.Integer,问题出在以下行obj1=(int)calStack.topAndpop()。问题是我的ArrayStack topAndpop()方法返回的对象类型为 public Object topAndpop() throws EmptyStackException{ Object returnPop; if (isEmpty())
obj1=(int)calStack.topAndpop()代码>。问题是我的ArrayStack topAndpop()方法返回的对象类型为
public Object topAndpop() throws EmptyStackException{
Object returnPop;
if (isEmpty())
throw new EmptyStackException("Stack empty");
else{
returnPop=top();
pop();
}
return returnPop;
我应该可以把它转换成int类型。除了这一行,我看不出有什么错误。有人能告诉我如何更正吗
import java.lang.Math;
public class Calculate{
double result=0;
int obj1,obj2;
public Object cal(String expression) throws OverFlowException,EmptyStackException{
String[] array = expression.split("");//remember
// for (int i=0;i<array.length;i++)
// System.out.println(array[i]);
ArrayStack calStack=new ArrayStack(array.length);
for(int i=0;i<array.length;i++){
if(!(array[i].equals("+") || array[i].equals("-")||array[i].equals("/") || array[i].equals("*"))){
calStack.push(array[i]);
//calStack.print();
}
else {
obj1=(int) calStack.topAndpop();//check how this casting is done
obj2=(int)calStack.topAndpop();
result=calculate(obj2,obj1,array[i]);
System.out.println(result);
calStack.push(result);
}
}
return calStack.topAndpop();
}
public double calculate(int a,int b,String op){
if(op=="+")
return a+b;
else if(op=="-")
return a-b;
else if(op=="/")
return a/b;
else if (op=="^")
return Math.pow(a,b);
else
return a*b;
}
public static void main (String args[]) throws OverFlowException,EmptyStackException{
Calculate c=new Calculate();
System.out.println("result"+c.cal("623+-382/+*2^3"));
}
import java.lang.Math;
公共类计算{
双结果=0;
int obj1、obj2;
公共对象cal(字符串表达式)引发OverFlowException,EmptyStackException{
String[]数组=表达式。拆分(“”;//还记得吗
//对于(int i=0;i而不是
obj1=(int) calStack.topAndpop();//check how this casting is done
obj2=(int)calStack.topAndpop();
使用:
您有不止一个问题,第一个字符串相等-
public double calculate(int a,int b,String op){
if(op.equals("+")) // <-- .equals! Not ==
return a+b;
else if(op.equals("-"))
return a-b;
else if(op.equals("/"))
return a/b;
else if(op.equals("^"))
return Math.pow(a,b);
else
return a*b;
}
问题出现在检查符号的if条件下,在此情况下,您错过了^
符号:
if(!(array[i].equals("+") || array[i].equals("-")
||array[i].equals("/") || array[i].equals("*"))){
为^
符号添加如下条件,代码将正常工作:
if(!(array[i].equals("+")
|| array[i].equals("-")
||array[i].equals("/")
|| array[i].equals("*"))
|| array[i].equals("^"))){
// do something
}
试着打印出你从堆栈中弹出的内容。发帖后,你发现这是问题的原因吗……还是其他原因?
if(!(array[i].equals("+") || array[i].equals("-")
||array[i].equals("/") || array[i].equals("*"))){
if(!(array[i].equals("+")
|| array[i].equals("-")
||array[i].equals("/")
|| array[i].equals("*"))
|| array[i].equals("^"))){
// do something
}