/**
* 加减乘除计算器
* 支持带括号的整数优先级运算
* 输入一个中缀表达式,符号与数字用空格隔开,例如 ( 1 + 2 ) * 3 - 4
* 输出运算结果
* */
import java.util.Scanner;
import java.util.Stack;
public class Calculator{
public static int getPriority(String op){ //获取操作符优先级
if(op.equals("+") || op.equals("-")){
return 1;
}else if(op.equals("*") || op.equals("/")){
return 2;
}else if(op.equals("(")){ //栈外括号优先级最大,栈内最小
return 0;
}else if(op.equals("=")){
return -1;
}else
return -1;
}
public static boolean isNum(String str){ //判断字符串是否为数字
if(str.charAt(0) == '-'){ //处理负数
if(str.length() == 1) {
return false;
}else {
for(int i = 1; i < str.length(); i++){
if(!Character.isDigit(str.charAt(i))){
return false;
}
}
}
}else {
for(int i = 0; i < str.length(); i++){
if(!Character.isDigit(str.charAt(i))){
return false;
}
}
}
return true;
}
public static int operation(int a,int b,String op){ //根据运算符进行运算
int result = 0;
if(op.equals("+"))
result = a + b;
else if(op.equals("-"))
result = a - b;
else if(op.equals("*"))
result = a * b;
else if(op.equals("/"))
result = a / b;
return result;
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String[] expr = str.split("\\s+"); //根据空格分割字符串
Stack<Integer> opNum = new Stack<Integer>(); //数字栈
Stack<String> opSign = new Stack<String>(); //操作符栈
opSign.push("=");
for(String s : expr){
if(isNum(s)){ //遇到数字,直接压栈
int num = Integer.parseInt(s);
opNum.push(num);
}else if(s.equals("(")){ //遇到左括号,直接压栈
opSign.push(s);
}
else if(s.equals(")")){
while(true) {
String op = opSign.pop();
if(op.equals("(")) //弹出左括号,结束
break;
else { //不是左括号,则为操作符,进行运算
int right = opNum.pop();
int left = opNum.pop();
int re = operation(left,right,op);
opNum.push(re);
}
}
}else{ //遇到的是+ - * /
while(true){
if(getPriority(s) > getPriority(opSign.peek())){
opSign.push(s); //当前符号优先级比栈顶符号优先级高,直接入栈
break;
}else{
int right = opNum.pop();
int left = opNum.pop();
String op = opSign.pop();
int re = operation(left,right,op);
opNum.push(re);
}
}
}
}
while(!opSign.peek().equals("=")){ //对栈中剩余数进行运算
int right = opNum.pop();
int left = opNum.pop();
String op = opSign.pop();
int re = operation(left,right,op);
opNum.push(re);
}
System.out.println(opNum.pop());
}
}
Java命令行计算器(中缀表达式求值)
最新推荐文章于 2023-04-21 11:41:29 发布