import com.yzk18.GUI.GUI;
import java.util.ArrayList;
import java.util.Stack;
public class 计算机 {
public static String trespass(String exp) {
StringBuilder out = new StringBuilder();
exp = exp.trim();
for (String x : exp.split("\\s+"))
out.append(x);
return out.toString();
}
public static ArrayList<String> infix(String exp) {
ArrayList<String> sb = new ArrayList<>();
char[] ch = exp.toCharArray();
for (int i = 0; i < ch.length; i++) {
StringBuilder in = new StringBuilder(String.valueOf(ch[i]));
while (Character.isDigit(ch[i]) && (i + 1) != ch.length && Character.isDigit(ch[i + 1])) {
i++;
in.append(ch[i]);
}
sb.add(in.toString());
}
return sb;
}
public static boolean digital(String x) {
boolean ju = true;
for (int i = 0; i < x.length(); i++) {
if (!Character.isDigit(x.charAt(i))) {
ju = false;
break;
}
}
return ju;
}
public static ArrayList<String> inflicts(ArrayList<String> infix) {
ArrayList<String> post = new ArrayList<>();
Stack<String> tack = new Stack<>();
for (String s : infix) {
if (digital(s)) {
post.add(s);
} else if (s.equals("(")) {
tack.push(s);
} else if (s.equals(")")) {
while (!tack.peek().equals("(")) {
post.add(tack.pop());
}
tack.pop();
} else {
if (s.equals("+") || s.equals("-")) {
while (!tack.empty()) {
if (!tack.peek().equals("("))
post.add(tack.pop());
else
break;
}
tack.push(s);
}
if (s.equals("*") || s.equals("/")) {
while (!tack.empty()) {
if (!tack.peek().equals("(") && !tack.peek().equals("+") && !tack.peek().equals("-"))
post.add(tack.pop());
else
break;
}
tack.push(s);
}
}
}
while (!tack.empty())
{
post.add(tack.pop());
}
return post;
}
public static Double PostCalculate(ArrayList<String> post) {
Stack<Double> calculate = new Stack<>();
for (String s : post) {
if (digital(s)) {
calculate.push(Double.valueOf(s));
}
if (s.equals("+")) {
Double x = calculate.pop();
Double y = calculate.pop();
Double z = y + x;
calculate.push(z);
}
if (s.equals("-")) {
Double x = calculate.pop();
Double y = calculate.pop();
Double z = y - x;
calculate.push(z);
}
if (s.equals("*")) {
Double x = calculate.pop();
Double y = calculate.pop();
Double z = y * x;
calculate.push(z);
}
if (s.equals("/")) {
Double x = calculate.pop();
Double y = calculate.pop();
Double z = y / x;
calculate.push(z);
}
}
return calculate.peek();
}
public static void main(String[] args) {
String s= GUI.inputBox("请输入表达式");
GUI.inputBox("结果为:",String.format("%.5f",PostCalculate(inflicts(infix(s)))));
System.out.print(s);
}
}
com.yzk18.GUI.GUI这个库需自行到https://mvnrepository.com/中下载 具体如何添加自己搜MAven