package shi;
import java.util.Random;
public class shi {
public static void main(String[] args) {
Random random = new Random();
int num1, num2, result = 0;
int operation;
for (int i = 0; i < 30; i++) {
// Generate random numbers between 1 and 100
num1 = random.nextInt(100) + 1;
num2 = random.nextInt(100) + 1;
// Generate random operation
operation = random.nextInt(4);
switch (operation) {
case 0:
// Addition
result = num1 + num2;
System.out.printf("%d + %d = ", num1, num2);
break;
case 1:
// Subtraction
if (num1 >= num2) {
result = num1 - num2;
System.out.printf("%d - %d = ", num1, num2);
} else {
// Swap num1 and num2 to ensure non-negative result
result = num2 - num1;
System.out.printf("%d - %d = ", num2, num1);
}
break;
case 2:
// Multiplication
result = num1 * num2;
System.out.printf("%d * %d = ", num1, num2);
break;
case 3:
// Division
if (num2 != 0) {
result = num1 / num2;
System.out.printf("%d / %d = ", num1, num2);
} else {
// Avoid division by zero
num2 = random.nextInt(100) + 1;
result = num1 / num2;
System.out.printf("%d / %d = ", num1, num2);
}
break;
}
System.out.println(result);
}
}
}
标签:num1,num2,random,System,result,课后练习,out
From: https://www.cnblogs.com/rglwx/p/18437081