1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
| public class Calculator {
public static void main(String[] args) { String expression = "300+2*2*2-1"; ArrayStack2 numStack = new ArrayStack2(10); ArrayStack2 operStack = new ArrayStack2(10); int index = 0; int num1 = 0; int num2 = 0; int oper = 0; int res = 0; char ch = ' '; String keepNum = ""; while(true) { ch = expression.substring(index,index+1).charAt(0); if(index == 0 && operStack.isOper(ch)) { throw new RuntimeException("表达式不规范"); } if(operStack.isOper(ch)) { if(!operStack.isEmpty()) { if(operStack.priority(operStack.peek())>=operStack.priority(ch)) { num2 = numStack.pop(); num1 = numStack.pop(); oper = operStack.pop(); res = numStack.cal(num1, num2, oper); numStack.push(res); index--; }else { operStack.push(ch); } }else { operStack.push(ch); } }else { keepNum +=ch; if(index == expression.length()-1) { numStack.push(Integer.parseInt(keepNum)); }else { if(operStack.isOper(expression.substring(index+1,index+2).charAt(0))) { numStack.push(Integer.parseInt(keepNum)); keepNum = ""; } } }
index++; if(index>=expression.length()) { break; } } while(true) { if(operStack.isEmpty()) { break; } num2 = numStack.pop(); num1 = numStack.pop(); oper = operStack.pop(); res = numStack.cal(num1, num2, oper); numStack.push(res); } int pop = numStack.pop(); System.out.println(pop); System.out.printf("计算: %s = %d",expression,pop);
}
|