java编写代码实现混合四则运算,需包含+、-、*、\及()的应用;例如输入实现(a+b)*c-d/2。
时间: 2024-09-19 08:06:14 浏览: 54
Java实现四则混合运算代码示例
在Java中,你可以使用栈数据结构以及解析字符串的方式来实现混合四则运算。这里是一个简单的示例,展示如何使用`eval()`函数或者自定义解析器来计算这样的表达式:
```java
import java.util.Stack;
public class MixedMath {
public static double calculate(String expression) {
Stack<Double> values = new Stack<>();
Stack<Character> operators = new Stack<>();
for (int i = 0; i < expression.length(); i++) {
char c = expression.charAt(i);
if (Character.isDigit(c)) {
double num = 0;
while (i + 1 < expression.length() && Character.isDigit(expression.charAt(i + 1))) {
num = num * 10 + (expression.charAt(i + 1) - '0');
i++;
}
i--;
values.push(num);
} else if (c == '(') {
operators.push(c);
} else if (c == ')') {
while (!operators.isEmpty() && operators.peek() != '(') {
double b = values.pop();
double a = values.pop();
char op = operators.pop();
switch (op) {
case '+':
values.push(a + b);
break;
case '-':
values.push(a - b);
break;
case '*':
values.push(a * b);
break;
case '/':
if (b != 0) {
values.push(a / b);
} else {
throw new IllegalArgumentException("Division by zero is not allowed.");
}
break;
}
}
if (!operators.isEmpty()) {
operators.pop(); // Pop the '('
}
} else if (operators.size() > 0 && precedence(c) <= precedence(operators.peek())) {
values.push(calculation(values, operators));
}
operators.push(c);
}
while (!operators.isEmpty()) {
double b = values.pop();
double a = values.pop();
char op = operators.pop();
switch (op) {
case '+':
values.push(a + b);
break;
case '-':
values.push(a - b);
break;
case '*':
values.push(a * b);
break;
case '/':
if (b != 0) {
values.push(a / b);
} else {
throw new IllegalArgumentException("Division by zero is not allowed.");
}
break;
}
}
return values.pop();
}
private static double precedence(char op) {
switch (op) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
default:
return 0;
}
}
private static double calculation(Stack<Double> values, Stack<Character> operators) {
double b = values.pop();
double a = values.pop();
char op = operators.pop();
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return a / b;
}
return 0; // This should never happen, but added as a safeguard
}
public static void main(String[] args) {
try {
System.out.println(calculate("(1 + 2) * 3 - 4 / 2")); // 输出结果:9.0
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
```
在这个例子中,我们遍历表达式的每个字符,处理数字、运算符和括号。注意这个示例使用了`calculation()`方法和`precedence()`方法来确保正确的运算顺序。
阅读全文