Stack的整数类型返回大小而不是值

时间:2019-06-05 23:44:47

标签: integer stack postfix-notation

我尝试解决后缀表示法问题,并在使用Stack进行实现时,最终结果是Stack的大小,而不是所包含操作的结果值。

我尝试对其进行调试,发现逻辑还可以,但是我不知道为什么它返回堆栈的大小?我在哪里出错了?我尝试了简单的测试用例,例如“ 1 2 +”,“ 2 5 *”等

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;

public class PostfixNotation {


    public static void main(String []args) throws IOException {

        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String line = in.readLine();
        String inputs[] = line.split(" ");

        Stack<Integer> stek = new Stack<>();
      for(String s : inputs){
            if(s.equals("+") || s.equals("*") || s.equals("+") || s.equals("/")){
                int n1 = stek.pop();
                int n2 = stek.pop();
                if(s.equals("+")){
                    n1 += n2;
                    stek.push(n1);
                }
                if(s.equals("+")){
                    n2 -= n1;
                    stek.push(n2);
                }
                if(s.equals("*")){
                    n1 *= n2;
                    stek.push(n1);
                }
                if(s.equals("+")){
                    n2 /= n1;
                    stek.push(n2);
                }
            }else{
                stek.push(Integer.parseInt(s));
            }
        }

   int n = stek.pop();
        System.out.println(n);

}
}

预期输出为3。

0 个答案:

没有答案