//匹配 publicstatic List<String> doMatch(String s)throws Exception { if (s == null || "".equals(s.trim())) thrownew RuntimeException("data is empty"); if (!isNumber(s.charAt(0) + "")) thrownew RuntimeException("data illeagle,start not with a number"); s = replaceAllBlank(s);
String each; int start = 0;
for (int i = 0; i < s.length(); i++) { if (isSymbol(s.charAt(i) + "")) { each = s.charAt(i) + ""; if (stack.isEmpty() || LEFT.equals(each) || ((calcLevel(each) > calcLevel(stack.peek())) && calcLevel(each) < LEVEL_HIGH)) { stack.push(each); } elseif (!stack.isEmpty() && calcLevel(each) <= calcLevel(stack.peek())) { while (!stack.isEmpty() && calcLevel(each) <= calcLevel(stack.peek())) { if (calcLevel(stack.peek()) == LEVEL_HIGH) { break; } data.add(stack.pop()); } stack.push(each); } elseif (RIGHT.equals(each)) { while (!stack.isEmpty() && LEVEL_HIGH >= calcLevel(stack.peek())) { if (LEVEL_HIGH == calcLevel(stack.peek())) { stack.pop(); break; } data.add(stack.pop()); } } start = i; } elseif (i == s.length() - 1 || isSymbol(s.charAt(i + 1) + "")) { each = start == 0 ? s.substring(start, i + 1) : s.substring(start + 1, i + 1); if (isNumber(each)) { data.add(each); continue; } thrownew RuntimeException("data not match number"); } } Collections.reverse(stack); data.addAll(new ArrayList<>(stack)); System.out.println(data); return data; }
//计算结果 publicstatic Double doCalc(List<String> list){ Double d = 0d; if(list == null || list.isEmpty()){ returnnull; } if(list.size() == 1){ System.out.println(list); d = Double.valueOf(list.get(0)); return d; } ArrayList<String> list1 = new ArrayList<>(); for (int i = 0; i < list.size(); i++) { list1.add(list.get(i)); if(isSymbol(list.get(i))){ Double d1 = doTheMath(list.get(i-2),list.get(i-1),list.get(i)); list1.remove(i); list1.remove(i-1); list1.set(i-2,d1+""); list1.addAll(list.subList(i+1,list.size())); break; } } doCalc(list1); return d; }
//运算 publicstatic Double doTheMath(String s1,String s2,String symbol){ Double result; switch (symbol){ case ADD: result = Double.valueOf(s1) + Double.valueOf(s2); break; case MINUS: result = Double.valueOf(s1) - Double.valueOf(s2); break; case TIMES: result = Double.valueOf(s1) * Double.valueOf(s2); break; case DIVISION: result = Double.valueOf(s1) / Double.valueOf(s2); break; default: result = null; } return result; }