import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static int location = 0; public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 String str = in.nextLine(); System.out.print(compute(str)); } public static int compute(String str){ int length = str.length(); int num = 0; char flag = '+'; ArrayList<Double> list = new ArrayList<>(); while(location < length){ if(str.charAt(location) == '{' || str.charAt(location) == '('|| str.charAt(location) == '['){ //如果表达式中含有括号,则单独对括号中的内容进行运算 location++; num = compute(str); } while(location < length && str.charAt(location) >= '0' && str.charAt(location) <= '9'){ //提取出表达式中的数字 num = num*10 + (str.charAt(location) - '0'); location++; } switch(flag){ //四则运算,先乘除后加减 //如果有加减运算,则等无乘除运算后在求解 case '+' : { list.add((double)num); break; } //将-修改为+号,最终是所有数求和 case '-' : { list.add((double)-num); break; } //如果有乘除运算,则直接运算 case '*' : { double temp = list.remove(list.size() - 1); temp *= (double)num; list.add(temp); break; } case '/' : { double temp = list.remove(list.size() - 1); temp /= (double)num; list.add(temp); break; } } num = 0; if(location == length) break; flag = str.charAt(location); if(str.charAt(location) == '}' || str.charAt(location) == ')'|| str.charAt(location) == ']'){ //遇到右侧括号,则表示当前层级求解已经结束 location++; break; } location++; } // 最终剩余的表达式没有括号,只有加法运算 int sum = 0; for(double i : list)sum+=i; return sum; } }
评论区递归解法的Java版本