写一个自动生成对于加减乘除混合运算用Java怎么写
时间: 2023-05-27 10:07:55 浏览: 138
1. 定义运算符和数字范围
首先,我们需要定义运算符和数字的范围。我们可以使用枚举类型来定义运算符,以及使用常量来定义数字的范围。例如:
```
enum Operator {
ADD, SUBTRACT, MULTIPLY, DIVIDE
}
public class Calculator {
private static final int MIN_NUMBER = 0;
private static final int MAX_NUMBER = 100;
}
```
2. 随机生成表达式
接下来,我们可以使用随机数生成器来生成表达式。我们可以使用一个方法来获取一个随机的运算符和数字,然后将它们组合成一个表达式。例如:
```
private static String generateExpression() {
Random random = new Random();
int number1 = random.nextInt(MAX_NUMBER - MIN_NUMBER) + MIN_NUMBER;
int number2 = random.nextInt(MAX_NUMBER - MIN_NUMBER) + MIN_NUMBER;
Operator operator = Operator.values()[random.nextInt(Operator.values().length)];
return number1 + " " + operator + " " + number2;
}
```
3. 计算表达式
最后,我们可以编写一个方法来计算表达式的值。我们可以将表达式拆分成数字和运算符,然后根据运算符执行相应的操作。例如:
```
private static int calculateExpression(String expression) {
String[] tokens = expression.split(" ");
int number1 = Integer.parseInt(tokens[0]);
int number2 = Integer.parseInt(tokens[2]);
Operator operator = Operator.valueOf(tokens[1]);
switch (operator) {
case ADD:
return number1 + number2;
case SUBTRACT:
return number1 - number2;
case MULTIPLY:
return number1 * number2;
case DIVIDE:
return number1 / number2;
default:
throw new IllegalArgumentException("Invalid operator: " + operator);
}
}
```
完整代码如下:
```
import java.util.Random;
enum Operator {
ADD, SUBTRACT, MULTIPLY, DIVIDE
}
public class Calculator {
private static final int MIN_NUMBER = 0;
private static final int MAX_NUMBER = 100;
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
String expression = generateExpression();
int result = calculateExpression(expression);
System.out.println(expression + " = " + result);
}
}
private static String generateExpression() {
Random random = new Random();
int number1 = random.nextInt(MAX_NUMBER - MIN_NUMBER) + MIN_NUMBER;
int number2 = random.nextInt(MAX_NUMBER - MIN_NUMBER) + MIN_NUMBER;
Operator operator = Operator.values()[random.nextInt(Operator.values().length)];
return number1 + " " + operator + " " + number2;
}
private static int calculateExpression(String expression) {
String[] tokens = expression.split(" ");
int number1 = Integer.parseInt(tokens[0]);
int number2 = Integer.parseInt(tokens[2]);
Operator operator = Operator.valueOf(tokens[1]);
switch (operator) {
case ADD:
return number1 + number2;
case SUBTRACT:
return number1 - number2;
case MULTIPLY:
return number1 * number2;
case DIVIDE:
return number1 / number2;
default:
throw new IllegalArgumentException("Invalid operator: " + operator);
}
}
}
```
阅读全文