服务器之家

服务器之家 > 正文

Java实现四则混合运算代码示例

时间:2021-01-14 15:52     来源/作者:joshuasabrina

使用栈来实现,可以处理运算优先级。

使用自然四则运算表达式即可,如:4+(3*(3-1)+2)/2。无需把表达式先转换为逆波兰等形式。

?
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
package com.joshua.cal;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
public class Calculator {
  private final Stack<Double> numStack = new Stack<Double>();
  private final Stack<Character> opStack = new Stack<Character>();
  private char currentOperator;
  private char opStackTop;
  private int i;
  private String expression;
  @SuppressWarnings("rawtypes")
  public void exec(String expression) {
    try {
      clean();
      if (expression == null || expression.isEmpty()) {
        throw new IllegalArgumentException("Blank Expression!");
      }
      this.expression = expression;
      opStack.push(TERMINATE_TOKENS.START_END_MARK);
      List tokens = TOKENIZER.exec(expression
          + TERMINATE_TOKENS.START_END_MARK);
      for (; i < tokens.size(); i++) {
        final Object token = tokens.get(i);
        if (token instanceof Double) {
          processOperand((double) token);
        } else {
          processOperator((char) token);
        }
      }
    } catch (Throwable e) {
      System.err.println(String.format(
          "Incorret Expression: %s\nError: %s", expression,
          e.getMessage()));
    }
  }
  private void processOperand(final double operand) {
    numStack.push(operand);
  }
  private void processOperator(final char currentOperator) {
    this.currentOperator = currentOperator;
    this.opStackTop = opStack.peek();
    char calMode = CALCULATE_MODE.getRule(currentOperator, opStackTop);
    switch (calMode) {
    case '>':
      processStackHigerPriorityOperator();
      break;
    case '<':
      processStackLowerPriorityOperator();
      break;
    case '=':
      processStackEqualPriorityOperator();
      break;
    default:
      break;
    }
  }
  private void processStackLowerPriorityOperator() {
    opStack.push(currentOperator);
  }
  private void processStackHigerPriorityOperator() {
    numStack.push(CALCULATE.exec(opStack.pop(), numStack.pop(),
        numStack.pop()));
    --i; // pointer back to the previous operator.
  }
  private void processStackEqualPriorityOperator() {
    if (TERMINATE_TOKENS.START_END_MARK == currentOperator) {
      System.out.println(expression + " = " + numStack.peek());
    } else if (')' == currentOperator) {
      opStack.pop();
    }
  }
  public void clean() {
    numStack.clear();
    opStack.clear();
    i = 0;
  }
  public static void main(String[] args) {
    Calculator cal = new Calculator();
    cal.exec("4+(3*(3-1)+2)/2"); // = 8
    cal.exec("4 + (-3 * ( 3 - 1 ) + 2)"); // = 0
    cal.exec("4 +-/ (-3 * ( 3 - 1 ) + 2)"); // incorrect expression!
    cal.exec("4.5+(3.2+3)/2"); // = 7.6
    cal.exec("4.5+(3.2:3)/2"); // incorrect expression!
    cal.exec("-4.5+(3.2-3)/2"); // = -4.4
  }
}
enum CALCULATE {
  INSTANCE;
  public static double exec(final char operator, final double right,
      final double left) {
    switch (operator) {
    case '+':
      return left + right;
    case '-':
      return left - right;
    case '*':
      return left * right;
    case '/':
      return left / right;
    default:
      throw new IllegalArgumentException("Unsupported operator: "
          + operator);
    }
  }
}
enum TERMINATE_TOKENS {
  INSTANCE;
  public static final char START_END_MARK = '#';
  private static final Map<Character, Integer> TOKENs = new HashMap<Character, Integer>();
  static {
    // token, token id
    TOKENs.put('+', 0);
    TOKENs.put('-', 1);
    TOKENs.put('*', 2);
    TOKENs.put('/', 3);
    TOKENs.put('(', 4);
    TOKENs.put(')', 5);
    TOKENs.put(START_END_MARK, 6);
  }
  private static Set<Character> NEGATIVE_NUM_SENSITIVE = new HashSet<Character>();
  public static synchronized Set<Character> getNegativeNumSensitiveToken() {
    if (NEGATIVE_NUM_SENSITIVE.size() == 0) {
      NEGATIVE_NUM_SENSITIVE.addAll(TOKENs.keySet());
      NEGATIVE_NUM_SENSITIVE.remove(')');
    }
    return NEGATIVE_NUM_SENSITIVE;
  }
  public static boolean isTerminateToken(final char token) {
    Set<Character> keys = TOKENs.keySet();
    return keys.contains(token);
  }
  public static int getTokenId(final char token) {
    return TOKENs.get(token) == null ? -1 : TOKENs.get(token);
  }
  public static int getTokenSize() {
    return TOKENs.size();
  }
}
enum CALCULATE_MODE {
  INSTANCE;
  private static char[][] RULES = {
      // + - * / ( ) #
      { '>', '>', '<', '<', '<', '>', '>' }, // +
      { '>', '>', '<', '<', '<', '>', '>' }, // -
      { '>', '>', '>', '>', '<', '>', '>' }, // *
      { '>', '>', '>', '>', '<', '>', '>' }, // /
      { '<', '<', '<', '<', '<', '=', 'o' }, // (
      { '>', '>', '>', '>', 'o', '>', '>' }, // )
      { '<', '<', '<', '<', '<', 'o', '=' }, // #
  };
  static {
    if (RULES.length != TERMINATE_TOKENS.getTokenSize() || RULES.length < 1
        || RULES[0].length != TERMINATE_TOKENS.getTokenSize()) {
      throw new IllegalArgumentException("Rules matrix is incorrect!");
    }
  }
  public static char getRule(final char currentOperator, final char opStackTop) {
    try {
      return RULES[TERMINATE_TOKENS.getTokenId(opStackTop)][TERMINATE_TOKENS
          .getTokenId(currentOperator)];
    } catch (Throwable e) {
      throw new RuntimeException("No rules were defined for some token!");
    }
  }
}
enum TOKENIZER {
  INSTANCE;
  private static final StringBuilder BUFFER = new StringBuilder();
  private static String clearExpression(String expression) {
    return expression.replaceAll(" ", "");
  }
  private static Character PREVIOUS_CHAR;
  private static void clean() {
    BUFFER.delete(0, BUFFER.length());
    PREVIOUS_CHAR = null;
  }
  private static boolean processNegativeNumbers(final String exp,
      final int index) {
    char c = exp.charAt(index);
    if (('+' == c || '-' == c)
        && (PREVIOUS_CHAR == null || TERMINATE_TOKENS
            .getNegativeNumSensitiveToken().contains(PREVIOUS_CHAR))
        && !TERMINATE_TOKENS.isTerminateToken(exp.charAt(index + 1))) {
      BUFFER.append(c);
      return true;
    }
    return false;
  }
  @SuppressWarnings({ "unchecked", "rawtypes" })
  public static List<?> exec(final String expression) {
    clean();
    String exp = clearExpression(expression);
    List result = new LinkedList();
    for (int i = 0; i < exp.length(); i++) {
      char c = exp.charAt(i);
      if (TERMINATE_TOKENS.isTerminateToken(c)) {
        if (processNegativeNumbers(exp, i))
          continue;
        if (BUFFER.length() > 0) {
          result.add(Double.valueOf(BUFFER.toString()));
          BUFFER.delete(0, BUFFER.length());
        }
        result.add(c);
      } else {
        BUFFER.append(c);
      }
      PREVIOUS_CHAR = c;
    }
    return Collections.unmodifiableList(result);
  }
}

 

输出

?
1
2
3
4
5
6
7
8
4+(3*(3-1)+2)/2 = 8.0
4 + (-3 * ( 3 - 1 ) + 2) = 0.0
4.5+(3.2+3)/2 = 7.6
-4.5+(3.2-3)/2 = -4.4
Incorret Expression: 4 +-/ (-3 * ( 3 - 1 ) + 2)
Error: null
Incorret Expression: 4.5+(3.2:3)/2
Error: For input string: "3.2:3"

总结

以上就是本文关于Java实现四则混合运算代码示例的全部内容,希望对大家有所帮助。有什么问题可以随时留言,小编会及时回复大家的。感谢朋友们对服务器之家网站的支持。

原文链接:http://joshuasabrina.iteye.com/blog/1947041

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享 2020-04-07
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部