【问题标题】:Postfix evaluation method in JavaJava中的后缀评估方法
【发布时间】:2018-03-27 12:22:11
【问题描述】:

所以我尝试为后缀评估方法编写代码,它给了我最离谱的结果。

我输入的后修复表达式是“92*3+4-”,根据我的计算,答案应该是 17。相反,我得到了 2849。这是怎么回事?

 public static int postFixEvaluator(String s){
    NewStack stack=new NewStack();
    for(int i=0;i<s.length();i++){
      if(Character.isDigit(s.charAt(i))) stack.push(s.charAt(i));

      else if(s.charAt(i)=='+'){
        int y=stack.pop();
        int x=stack.pop();
        int z=(int)(x+y);
        stack.push((char)(z));
        //System.out.println(z);
      }
      else if(s.charAt(i)=='-'){
        int y=stack.pop();
        int x=stack.pop();
        int z=x-y;
        stack.push((char)(z));
      }
      else if(s.charAt(i)=='*'){
        int y=stack.pop();
        int x=stack.pop();
        int z=x*y;
        stack.push((char)(z));
        System.out.println(x*y);
      }
      else if(s.charAt(i)=='/'){
        int y=stack.pop();
        int x=stack.pop();
        int z=x/y;
        stack.push((char)(z));
      }
      else if(s.charAt(i)=='%'){
        int y=stack.pop();
        int x=stack.pop();
        int z=x%y;
        stack.push((char)(z));
      }
    }
    return stack.pop();
  }




enter code here

【问题讨论】:

    标签: data-structures stack postfix-notation


    【解决方案1】:

    基本问题是您正在推动字符和弹出整数。也就是说,你有:

    if(Character.isDigit(s.charAt(i))) stack.push(s.charAt(i));
    

    所以如果字符是3,你会将3压入堆栈。

    但是当你弹出时,你有:

    int y=stack.pop();
    

    字符3的整数表示为51。

    当您将结果推回堆栈时,情况会变得更糟。如果堆栈中有字符 3 和 4,则最终将 51 和 52 相加,然后将 103 推回堆栈。但在某些时候,你会超出角色的大小,事情就会完全偏离轨道。

    我的建议是创建一个整数堆栈,然后将整数压入堆栈。所以你上面的陈述变成了:

    if(Character.isDigit(s.charAt(i)))
    {
        stack.push(Character.GetNumericValue(s.charAt(i)));
    }
    

    在您的操作代码中,替换

    stack.push((char)(z));
    

    stack.push(z);
    

    【讨论】:

      猜你喜欢
      • 2018-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-26
      • 2012-03-10
      • 2013-12-21
      • 2015-05-03
      • 1970-01-01
      相关资源
      最近更新 更多