用java写一个简单的四则运算包含括号
时间: 2023-08-12 07:02:20 浏览: 198
以下是一个使用Java编写的简单的四则运算包含括号的示例:
```java
import java.util.Scanner;
public class ArithmeticCalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入四则运算表达式:");
String expression = input.nextLine();
input.close();
try {
int result = calculate(expression);
System.out.println("计算结果是:" + result);
} catch (IllegalArgumentException e) {
System.out.println("无效的表达式!");
}
}
public static int calculate(String expression) {
// 去除空格
expression = expression.replaceAll("\\s", "");
// 利用栈进行运算
ArrayStack<Integer> numberStack = new ArrayStack<>();
ArrayStack<Character> operatorStack = new ArrayStack<>();
for (int i = 0; i < expression.length(); i++) {
char c = expression.charAt(i);
if (Character.isDigit(c)) {
// 读取数值
int number = c - '0';
while (i + 1 < expression.length() && Character.isDigit(expression.charAt(i + 1))) {
number = number * 10 + (expression.charAt(i + 1) - '0');
i++;
}
numberStack.push(number);
} else if (c == '(') {
// 左括号入栈
operatorStack.push(c);
} else if (c == ')') {
// 右括号内的表达式进行计算
while (!operatorStack.isEmpty() && operatorStack.peek() != '(') {
calculate(operatorStack, numberStack);
}
// 弹出左括号
operatorStack.pop();
} else if (c == '+' || c == '-' || c == '*' || c == '/') {
// 将栈内优先级大于等于当前操作符的操作符先进行计算
while (!operatorStack.isEmpty() && operatorStack.peek() != '(' && compareOperator(c, operatorStack.peek())) {
calculate(operatorStack, numberStack);
}
// 当前操作符入栈
operatorStack.push(c);
} else {
throw new IllegalArgumentException("无效的字符:" + c);
}
}
// 计算剩余的操作符
while (!operatorStack.isEmpty()) {
calculate(operatorStack, numberStack);
}
// 返回最终结果
if (numberStack.getSize() != 1 || !operatorStack.isEmpty()) {
throw new IllegalArgumentException("无效的表达式!");
}
return numberStack.pop();
}
private static void calculate(ArrayStack<Character> operatorStack, ArrayStack<Integer> numberStack) {
int num2 = numberStack.pop();
int num1 = numberStack.pop();
char operator = operatorStack.pop();
int result = 0;
if (operator == '+') {
result = num1 + num2;
} else if (operator == '-') {
result = num1 - num2;
} else if (operator == '*') {
result = num1 * num2;
} else if (operator == '/') {
if (num2 == 0) {
throw new IllegalArgumentException("除数不能为0!");
}
result = num1 / num2;
}
numberStack.push(result);
}
private static boolean compareOperator(char op1, char op2) {
if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-')) {
return true;
}
return false;
}
}
```
这个程序首先会要求用户输入一个四则运算表达式,然后利用栈来进行运算。运算过程中会先计算括号内的表达式,最后输出计算结果。如果输入的表达式不合法,会抛出`IllegalArgumentException`异常。
阅读全文