我的任務是使用array和char爲postfix評估創建一個程序。 我遇到問題錯誤不兼容的類型。 Postfix評估
不兼容的類型:對象不能轉換爲int。
這裏是我的代碼:
import java.util.*;
public class StackPostfixEva { //class name
public static void main(String args[]) {
Scanner key = new Scanner(System.in); //initialize scanner
char[] postfix = new char[10]; //creating array
System.out.println("Please enter postfix expression. Enter '#' if you have finish entering postfix expression "); //instruction command
int i; //initialize variable
for (i = 0; i <= postfix.length; i++) { //loop for receiving input
postfix[i] = key.next().charAt(i); //input command
if (postfix[i] == '#') { //to indicate the end
break;
}
}
System.out.println("The postfix expression are:"); //to print postfix
expression
for (i = 0; i <= postfix.length; i++) {
System.out.println(postfix[i]);
}
Stack st = new Stack(); //creating stack
int result, ch1, ch2; //initialize variable
for (i = 0; i <= postfix.length; i++) { //loop for scanning each char
if (postfix[i] >= '0' && postfix[i] <= '9') { //to determine operand
st.push((int) postfix[i] - '0'); //push operand
}
else
{ //execution if operator found
ch1 = st.pop(); //problem here
ch2 = st.pop(); //problem here
switch (postfix[1]) {
case '+':
result = ch2 + ch1;
break;
case '-':
result = ch2 - ch1;
break;
case '*':
result = ch2 * ch1;
break;
case '/':
result = ch2/ch1;
break;
case '%':
result = ch2/ch1;
break;
default:
result = 0;
} //end switch
st.push(result);
} //end else
} //end for
result = st.pop(); //problem here
System.out.println(result);
}
}
感謝您的解決方案。但是現在我遇到了ArrayIndexOutOfBound異常。 >。< –
用ArrayIndexOutOfBound異常完成,但EmptyStack異常後來。 –
你需要調試你的代碼,看看爲什麼在一個空棧上調用'pop()'操作。任何像樣的IDE(例如,IDEA,Eclipse,Netbeans)都包含一個調試器,它可以在執行代碼時逐步執行代碼,並查看變量發生的情況。 –