使用字符串数组和整数堆栈(Java)进行Postfix评估

时间:2019-07-29 07:12:46

标签: java postfix-notation

这是正常的后缀评估问题。

输入:

2 (testcases)
231*+9-
123+*8-

输出:

-4
-3

我已经浏览了可用的问题,但使用我的方法找不到任何人。我对此很陌生,所以不确定我的方法是否正确,这是一项作业,我只想知道我的方法出了什么问题。

import java.util.*;
import java.lang.*;
import java.io.*;
class dmn
 {
    public static void main (String[] args)
     {
         Scanner sc=new Scanner(System.in);
         int t= sc.nextInt();
         while(t-->0){
             String s= sc.nextLine();
             String [] sToCharArray = s.split("");
             Stack <Integer> st =new Stack<Integer>();
             for(String token:sToCharArray){
                 if(token.equals("/")){
                    int op1=st.pop();
                    int op2=st.pop();
                    int res=op1/op2;
                     st.push(res);

                 }
                 else if(token.equals("*")){
                    int op1=st.pop();
                    int op2=st.pop();
                    int res=op1*op2;
                     st.push(res);
                 }
                 else if(token.equals("+")){
                   int  op1=st.pop();
                    int op2=st.pop();
                    int res=op1+op2;
                     st.push(res);
                     //System.out.println(st);
                 }
                 else if(token.equals("-")){
                    int op1=st.pop();
                    int op2=st.pop();
                    int res=op1-op2;
                     st.push(res);
                 }
                 else{
                     st.push(Integer.parseInt(token));
                     }
             }
             System.out.println(st.pop());
         }


     }
}

时间(秒):0.1内存(MB):56.0117

Runtime Errors:Exception in thread "main" java.lang.NumberFormatException: For input string: "" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:592)
    at java.lang.Integer.parseInt(Integer.java:615)
    at dmn.main(File.java:43)

0 个答案:

没有答案