用java随机生成10以内的整数混合运算
时间: 2024-02-23 16:01:45 浏览: 61
如何用java生成指定范围的随机数
可以使用Java的Math类中的随机数生成方法和基本的四则运算符来生成10以内的整数混合运算,示例代码如下:
```java
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random random = new Random();
int num1 = random.nextInt(10) + 1; // 生成1~10之间的随机整数
int num2 = random.nextInt(10) + 1;
int num3 = random.nextInt(10) + 1;
int oper1 = random.nextInt(4); // 生成0~3之间的随机整数,对应加减乘除运算
int oper2 = random.nextInt(4);
int result = 0;
switch (oper1) { // 根据随机数生成的运算符来进行运算
case 0:
result = num1 + num2;
break;
case 1:
result = num1 - num2;
break;
case 2:
result = num1 * num2;
break;
case 3:
result = num1 / num2;
break;
}
switch (oper2) {
case 0:
result += num3;
break;
case 1:
result -= num3;
break;
case 2:
result *= num3;
break;
case 3:
result /= num3;
break;
}
System.out.println(num1 + " " + getOperator(oper1) + " " + num2 + " " + getOperator(oper2) + " " + num3 + " = " + result);
}
public static String getOperator(int oper) { // 根据随机数生成的运算符来返回对应的符号
switch (oper) {
case 0:
return "+";
case 1:
return "-";
case 2:
return "*";
case 3:
return "/";
}
return "";
}
}
```
运行代码会输出类似以下的结果:
```
4 + 9 * 2 = 22
```
阅读全文