2017-08-14 18 views
0

私の仕事は、arrayとcharを使って後置評価用のプログラムを作ることです。 問題に問題がありますエラーに互換性のないタイプです。 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); 
    } 
} 

答えて

1

あなただけInteger値を格納するために、あなたのスタックを使用しているので、私はジェネリック型を指定することをお勧めしたい:

Stack<Integer> st = new Stack<>(); 

st.pop()はタイプIntegerを持つことになりますし、intにautoboxedされる方法を。

あなたはそれを宣言するとStack(別の答えで提供)明示的なキャストなしintに変換できないpop()戻りObject、(なし型パラメータを持つ)など。

+0

あなたのソリューションの仕事に感謝します。しかし、今はArrayIndexOutOfBoundの例外があります。 >。< –

+0

ArrayIndexOutOfBound例外は終了しましたが、EmptyStack例外がすぐに発生しました。 –

+0

空のスタック上で 'pop()'オペレーションが呼び出される理由を調べるには、コードをデバッグする必要があります。まともなIDE(例えば、IDEA、Eclipse、Netbeans)には、コードが実行されるときにステップを踏み、変数がどうなるかを見るためのデバッガが含まれています。 –

0

あなたは整数に変換する必要があります。

ch1 = Integer.parseInt(st.pop()); 
ch2 = Integer.parseInt(st.pop()); 
+0

この解決策は機能しませんでした。同じエラーが出るだけです。 –

関連する問題