最近在看数据结构的内容,自己按照思路写了一个Java版的计算器,可以通过计算式得出计算结果,当然对于数据验证没做太多详细的验证,仅仅是为了展示栈的使用情况:代码如下,
public class TestaAAA {
String sss = "*/";
String plus = "+-";
public static void main(String[] args) {
String text = "19.56 +(3 -1)*3+10/2";
double calculate = calculate(text);
System.out.println(calculate);
}
private static double calculate(String text) {
text = text.replace(" ", "");
Stack<String> calculate = new Stack<>();
List<String> list = new ArrayList<>();
Stack<Character> stack = new Stack<>();
for (int i = 0; i < text.length(); i++) {
StringBuilder num = new StringBuilder();
Character c = text.charAt(i);
int x = i;
while (c.toString().matches("\\d")||c.toString().equals(".")) {
num.append(c);
if (i == text.length() - 1) {
break;
}
x++;
c = text.charAt(x);
}
int i1 = x - i;
if (i1 > 1) {
i += i1 - 1;
}
if (num.length() != 0) {
list.add(num.toString());
} else {
if (stack.empty()) {
stack.push(c);
} else {
Object o = stack.peek();
Character o1 = (Character) o;
int c_lvl = getlvl(c);
int top_lvl = getlvl(o1);
if (c == '(') {
stack.push(c);
} else if (c == ')') {
Object pop = stack.pop();
while (!pop.toString().equals("(")) {
list.add(pop.toString());
if (stack.empty()) {
break;
}
pop = stack.pop();
}
} else if (top_lvl == 3) {
stack.push(c);
} else if (c_lvl < top_lvl) {
while (!stack.empty()) {
Object pop = stack.pop();
list.add(pop.toString());
}
stack.push(c);
} else {
stack.push(c);
}
}
}
}
while (!stack.empty()) {
Object pop = stack.pop();
list.add(pop.toString());
}
for (String s : list) {
if (isNum(s)) {
calculate.push(s);
} else {
String topValue = calculate.pop();
String top2Value = calculate.pop();
String s1 = calculateNum(s, top2Value, topValue);
if (s1 != null) {
calculate.push(s1);
}
}
}
String pop = calculate.pop();
return Double.valueOf(pop);
}
private static String calculateNum(String s, String topValue, String top2Value) {
Double value1 = Double.valueOf(topValue);
Double value2 = Double.valueOf(top2Value);
if ("+".equals(s)) {
Double v = value1 + value2;
return v.toString();
}
if ("-".equals(s)) {
Double v = value1 - value2;
return v.toString();
}
if ("*".equals(s)) {
Double v = value1 * value2;
return v.toString();
}
if ("/".equals(s)) {
Double v = value1 / value2;
return v.toString();
}
return null;
}
private static int getlvl(char c) {
if ("+-".contains(String.valueOf(c))) {
return 1;
}
if ("*/".contains(String.valueOf(c))) {
return 2;
}
return 3;
}
private static boolean isNum(String str) {
Double aDouble = null;
try {
aDouble = Double.valueOf(str);
} catch (NumberFormatException ignored) {
}
return aDouble != null;
}
}