需要帮助在Postfix评估上实现Java算法吗
我试着从头开始编写代码,编写代码并运行它,但它似乎不起作用。这是课堂上的实验作业。这些要求是: 使用堆栈和堆栈操作(用户定义)实现后缀计算。 我认为我的程序的算法是正确的,但它总是给我错误的答案。 这是我的密码需要帮助在Postfix评估上实现Java算法吗,java,stack,postfix-notation,Java,Stack,Postfix Notation,我试着从头开始编写代码,编写代码并运行它,但它似乎不起作用。这是课堂上的实验作业。这些要求是: 使用堆栈和堆栈操作(用户定义)实现后缀计算。 我认为我的程序的算法是正确的,但它总是给我错误的答案。 这是我的密码 public class StackApplication { public static class Stack<T> { private int top = 0; private final static int stackMa
public class StackApplication {
public static class Stack<T> {
private int top = 0;
private final static int stackMax=100;
// highest index of stk array
private Object[] stk = new Object[stackMax+1];
//Elements must be cast back.
public Stack() { // constructor
}
public boolean isEmpty(){
if (top==0) return true;
else return false;
}
public void push(T el) {
if(top==stackMax)
System.out.println("Stack push overflow error");
else top=top+1;
stk[top]=el;
}
public T pop(){
if(isEmpty()){
System.out.println("Stack push underflow error");
return null;
}
else top=top-1;
return(T)stk[top+1];
}
public T top(){
if(isEmpty()){
//System.out.println("Stack empty");
return null;
}
else return (T)stk[top];
}
}
public static boolean isOperator(char c){
return(c=='+' || c=='-' || c=='/' || c=='*' || c=='^');
}
public static double evaluate(double x, char o, double y) {
double result=0;
switch(o) {
case '+' : result=x+y; break;
case '-' : result=x-y; break;
case '*' : result=x*y; break;
case '/' : result=x/y; break;
case '^' : result=Math.pow(x, y); break;
default : break;
}
return result;
}
public static void main(String[] args) {
Scanner console=new Scanner(System.in);
Stack<Double> s=new Stack<Double>();
System.out.println("Input Postfix form to evaluate:");
String inp=console.nextLine();
char[] chararray=inp.toCharArray();
double b,a;
for(int i=0; i<chararray.length; i++) {
if(!isOperator(chararray[i]))
s.push((double)chararray[i]);
else {
b=s.pop();
a=s.pop();
double c=evaluate(a, chararray[i], b);
s.push(c);
}
}
System.out.println(" " +s.pop());
}
}
问题就在这里:
s.push((双)字符[i])代码>。您不能用这种方式将char
转换为double
。您现在使用的是2
和3
的ascii码
50(2的ascii码)+51(3的ascii码)=101
这样做:s.push((double)(chararray[i]-'0')代码>您正在为2和3添加ASCII代码,而不是为2和3添加ASCII代码
2的代码是50,3的代码是51,所以out是101,这在本例中是正确的
按下时,按下chararray[i]-“0”
。这将解决您的问题。对于此类问题,我认为您最好调试该问题。如下面的注释所示,如果您曾经尝试进入类ExecutionThank,您将很容易找到这个根本原因。我现在意识到,在操作中,铸造双倍是没有意义的。不幸的是,强制转换到任何数据类型并不等于解析。谢谢你的帮助。
23+ (Input)
101.0 (Output)
5.0 (Expected output)