简单计算器(考虑小括号和运算符号优先级)
例如:
输入: 1+((2+3)*4)-5*1.5
输出: 1+((2+3)*4)-5*1.5=13.5
输入: (2+1)*1.5
输出: (2+1)*1.5=4.5
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
List <String> arrayList = getArrayList(s);
// System.out.println(arrayList);
List <String> list = work(arrayList);
//System.out.println(list);
System.out.println(s+"="+finash(list));
}
public static List <String> getArrayList(String s) {
List <String> list = new ArrayList <String>();
String s2 = "";
for (int i = 0; i < s.length(); i++) {
//如果是数
if (!isOper(s.charAt(i))) {
s2 += s.charAt(i);
//如果是多位数
if (i == s.length() - 1 || isOper(s.charAt(i+1))) {
list.add(s2);
s2 = "";
}
} else {
list.add("" + s.charAt(i));
}
}
return list;
}
public static List <String> work(List <String> list) {
Stack <String> s1 = new Stack <>();
List <String> s2 = new ArrayList <>();
for (String item : list) {
if (item.matches("^(\\-|\\+)?\\d+(\\.\\d+)?$")) {
s2.add(item);
} else if (item.equals("(") || s1.size() == 0) {
s1.push(item);
} else if (item.equals(")")) {
while (!s1.peek().equals("(")) {
s2.add(s1.pop());
}
s1.pop();//把”(“给清除
} else {//item是加减乘除
//如果item的优先级比较高
if (op(item) > op(s1.peek()))
s1.push(item);
//如果item的优先级比较低
else {
while (s1.size() != 0 && op(item) <= op(s1.peek())) {
s2.add(s1.pop());
}
s1.push(item);
}
}
}
while (s1.size() != 0) {
s2.add(s1.pop());
}
return s2;
}
public static int op(String oper) {
if (oper.equals("+") || oper.equals("-")) {
return 1;
} else if (oper.equals("*") || oper.equals("/")) {
return 2;
} else if (oper.equals("(")) {
return 0;
} else {
throw new RuntimeException("ERROR!运算符号有误...");
}
}
public static double finash(List <String> list) {
Stack <Double> stringStack = new Stack <>();
double num1 = 0;
double num2 = 0;
double result = 0;
String op = "";
for (String item : list) {
if (item.matches("^(\\-|\\+)?\\d+(\\.\\d+)?$")) {
stringStack.push(Double.parseDouble(item));
} else {
switch (item) {
case "+":
num1 = stringStack.pop();
num2 = stringStack.pop();
result = num2 + num1;
stringStack.push(result);
break;
case "-":
num1 = stringStack.pop();
num2 = stringStack.pop();
result = num2 - num1;
stringStack.push(result);
break;
case "*":
num1 = stringStack.pop();
num2 = stringStack.pop();
result = num2 * num1;
stringStack.push(result);
break;
case "/":
num1 = stringStack.pop();
num2 = stringStack.pop();
if (num1 == 0) {
throw new RuntimeException("ERROR: " + num2 + "/" + num1);
}
result = num2 / num1;
stringStack.push(result);
break;
}
}
}
return stringStack.pop();
}
public static Boolean isOper(char oper) {
return oper == '+' || oper == '-' || oper == '*' || oper == '/' || oper == '(' ||oper == ')';
}
}
本文介绍了一个Java程序,演示了如何使用栈来处理带有小括号和运算符的简单计算器,通过优先级解析实现复杂算术表达式的计算。
7353

被折叠的 条评论
为什么被折叠?



