这是后缀计算器程序,我收到一个无法识别的操作数错误

时间:2014-02-01 05:16:17

标签: java java.util.scanner postfix-notation

import java.util.Scanner;

public class BS {

public static void main (String [] args){
    LinkedStack s = new LinkedStack();
    String a = " 1 6 /";
    Scanner t = new Scanner(a);
    int result = 0;

    while(t.hasNext()){
        if(t.hasNextInt()){
            s.push(t.nextInt());                
        }           
        else
        {               
            String operator = t.next();         
            System.out.println(operator);

            int op1, op2;

            if(s.isEmpty())
                throw new RuntimeException ("not enough operants");


            op2 = s.pop();

            if(s.isEmpty())
                throw new RuntimeException ("not enough operator");

            op1 = s.pop();          

            if(operator.equals('+'))
                result = op2 + op1;
            if(operator.equals('-'))
                result = op2-op1;
            if(operator.equals('*'))
                result = op2*op1;
            if(operator.equals('/'))
                result = op2/op1;               
            else 
                throw new RuntimeException ("unrecognize operands");
        }           
    }

    System.out.println(result);     
    }
}

这是后缀计算器程序。但由于某种原因,我得到了无法识别的操作数错误。 该程序无法识别'/'符号。我不知道为什么?

2 个答案:

答案 0 :(得分:0)

if阻止错误。 else仅适用于上一个if。它应该是

        if(operator.equals('+'))
            result = op2 + op1;
        else if(operator.equals('-'))
            result = op2-op1;
        else if(operator.equals('*'))
            result = op2*op1;
        else if(operator.equals('/'))
            result = op2/op1;
        else 
            throw new RuntimeException ("unrecognize operands");

答案 1 :(得分:0)

你问过识别'/'号。除了修复@Johnny Mopp建议的if块之外,主要问题是您应该比较从java.util.Scanner读取的字符串而不是字符。更改此以及所有其他操作数来比较字符串:

if(operator.equals("/"))
    result = op2/op1; 

以下是您的代码正在使用并打印6http://ideone.com/HVAqQX