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 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
| import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.Stack;
public class PolandNotation { public static void main(String[] args) { String suffixExpression = "4 5 * 8 - 60 + 8 2 / +";
List<String> list = getListString(suffixExpression); System.out.println("rpnList= " + list); int res = calculate(list); System.out.println("the Result = " + res);
System.out.println("========请输入中缀表达式,俺们自动计算========="); Scanner sc = new Scanner(System.in); String expression = sc.next(); List<String> expList = toExpressionList(expression); List<String> suffixExpList = parseSuffixExpressionList(expList); int res2 = calculate(suffixExpList); System.out.println("Great, your expression Result = " + res2); }
public static List<String> parseSuffixExpressionList(List<String> ls){ Stack<String> s1 = new Stack<>(); List<String> s2 = new ArrayList<>();
for (String item : ls){ if (item.matches("\\d+")){ s2.add(item); }else if (item.equals("(")){ s1.push(item); }else if (item.equals(")")){ while (!s1.peek().equals("(")){ s2.add(s1.pop()); } s1.pop(); }else { while (s1.size() != 0 && Operation.getVlaue(s1.peek()) >= Operation.getVlaue(item)){ s2.add(s1.pop()); } s1.push(item); } } while (s1.size() != 0){ s2.add(s1.pop()); } return s2; }
public static List<String> toExpressionList(String s){ List<String> ls = new ArrayList<>(); int i = 0; String str; char c; do{ if ((c=s.charAt(i)) < 48 || (c=s.charAt(i)) > 57){ ls.add("" + c); i++; }else { str = ""; while (i < s.length() && (c=s.charAt(i)) >= 48 && (c=s.charAt(i)) <= 57){ str += c; i++; } ls.add(str); } }while (i < s.length());
return ls; }
public static List<String> getListString(String suffixExpression){ String[] split = suffixExpression.split(" "); List<String> list = new ArrayList<>(); for (String ele : split){ list.add(ele); } return list; }
public static int calculate(List<String> ls){ Stack<String> stack = new Stack<String>(); for (String item : ls){ if (item.matches("\\d+")){ stack.push(item); }else{ int num2 = Integer.parseInt(stack.pop()); int num1 = Integer.parseInt(stack.pop()); int res = 0; if (item.equals("+")) { res = num1 + num2; }else if (item.equals("-")){ res = num1 - num2; }else if (item.equals("*")){ res = num1 * num2; }else if (item.equals("/")){ res = num1 / num2; }else { throw new RuntimeException("Sorry, we DONOT support the operator now!"); } stack.push("" + res); } } return Integer.parseInt(stack.pop()); } }
|