用Java语言用栈运算方法用解释器模式实现两位数的简单加减法运算,例如输入参数为字符串“10+20-15”,运行可以得到结果=15
时间: 2024-05-14 20:16:16 浏览: 72
以下是一个简单的实现:
首先定义一个接口,用于表示解释器的抽象语法树节点:
```java
interface Node {
int interpret();
}
```
然后定义具体的节点类:
```java
class NumberNode implements Node {
private int number;
public NumberNode(int number) {
this.number = number;
}
public int interpret() {
return number;
}
}
class AddNode implements Node {
private Node left, right;
public AddNode(Node left, Node right) {
this.left = left;
this.right = right;
}
public int interpret() {
return left.interpret() + right.interpret();
}
}
class SubNode implements Node {
private Node left, right;
public SubNode(Node left, Node right) {
this.left = left;
this.right = right;
}
public int interpret() {
return left.interpret() - right.interpret();
}
}
```
然后定义解释器类:
```java
class Interpreter {
private Stack<Node> stack = new Stack<Node>();
public int interpret(String input) {
String[] tokens = input.split("\\s+");
for (String token : tokens) {
if (isNumber(token)) {
stack.push(new NumberNode(Integer.parseInt(token)));
} else if (token.equals("+")) {
Node right = stack.pop();
Node left = stack.pop();
stack.push(new AddNode(left, right));
} else if (token.equals("-")) {
Node right = stack.pop();
Node left = stack.pop();
stack.push(new SubNode(left, right));
}
}
return stack.pop().interpret();
}
private boolean isNumber(String s) {
try {
Integer.parseInt(s);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
```
最后在主函数中调用解释器类:
```java
public static void main(String[] args) {
Interpreter interpreter = new Interpreter();
int result = interpreter.interpret("10 20 - 15");
System.out.println("result = " + result);
}
```
运行结果:
```
result = 15
```
阅读全文