首页 > 代码库 > Java表达式求值
Java表达式求值
import java.math.BigInteger;import java.util.*;public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); while(scan.hasNext()) { String str1 = scan.next(); Stack<BigInteger> num = new Stack<BigInteger>(); Stack<Character> op = new Stack<Character>(); // +,-,*,/,^,() for(int i=0;i<str1.length();i++) { char ch = str1.charAt(i); switch(ch) { case ‘+‘: case ‘-‘: // 这些优先级都大于等于当前操作符 while(!op.empty() && (op.peek()==‘+‘ || op.peek()==‘-‘ || op.peek()==‘*‘ || op.peek()==‘/‘ || op.peek()==‘^‘)) { calc_stack(num, op); } op.push(ch); break; case ‘*‘: case ‘/‘: while(!op.empty() && (op.peek()==‘*‘ || op.peek()==‘/‘ || op.peek()==‘^‘)) { calc_stack(num, op); } op.push(ch); break; case ‘^‘: while(!op.empty() && op.peek()==‘^‘) { calc_stack(num, op); } op.push(ch); break; case ‘(‘: op.push(ch); break; case ‘)‘: while(op.peek()!=‘(‘) { calc_stack(num, op); } // ‘(‘出栈 op.pop(); break; default: String number = String.valueOf(ch); while(i+1<str1.length() && Character.isDigit(str1.charAt(i+1))) { number +=String.valueOf(str1.charAt(i+1)); i++; } BigInteger big = new BigInteger(number); num.push(big); break; } } while(!op.empty()) { calc_stack(num, op); } System.out.println(num.pop()); } scan.close(); } private static void calc_stack(Stack<BigInteger>num, Stack<Character>op) { char operator = op.pop(); BigInteger num1 = num.pop(); BigInteger num2 = num.pop(); switch(operator) { case ‘+‘: num.push(num2.add(num1));break; case ‘-‘: num.push(num2.subtract(num1));break; case ‘*‘: num.push(num2.multiply(num1));break; case ‘/‘: num.push(num2.divide(num1));break; case ‘^‘: num.push(num2.pow(num1.intValue()));break; } }}
Java表达式求值
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。