java_day17

目标:Java web开发

问题:表达式求值

import java.io.*;
import java.util.*;
public class Main{
    static BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
    public static void main(String[] args) throws IOException{
        Stack<Character> ops=new Stack<Character>();
        Stack<Integer> nums=new Stack<>();//自动检测
        HashMap<Character,Integer> mp=new HashMap<>();
        mp.put('+',1);
        mp.put('-',1);
        mp.put('*',2);
        mp.put('/',2);
        mp.put('(',-1);
        char[] str=in.readLine().toCharArray();
        StringBuilder sb=new StringBuilder();
        for(int i=0;i<str.length;i++){
            char c=str[i];
            if(Character.isDigit(c)){
                sb.append(c);
                int j=i+1;
                while(j<str.length&&Character.isDigit(str[j])){
                    sb.append(str[j]);
                    j++;
                }
                nums.push(Integer.parseInt(sb.toString()));
                sb.delete(0,sb.length());
                i=j-1;
            }
            else if(c=='(') ops.push(c);
            else if(c==')'){
                while(ops.peek()!='(') eval(ops,nums);
                ops.pop();
            }
            else{
                while(!ops.isEmpty()&&(mp.get(ops.peek())>=mp.get(c))) eval(ops,nums);
                ops.push(c);
            }
        }
        while(!ops.empty()) eval(ops,nums);
        System.out.println(nums.peek());
    }
    static void eval(Stack<Character> ops,Stack<Integer> nums){
        int num1=nums.pop();
        int num2=nums.pop();
        char op=ops.pop();
        if(op=='+') nums.push(num1+num2);
        else if(op == '-') nums.push(num2-num1);
        else if(op == '*') nums.push(num1*num2);
        else nums.push(num2/num1);
    }
}
posted @ 2021-07-23 21:59  zhuangzhongxu  阅读(37)  评论(0)    收藏  举报