我被赋予了创建一个真正随机的计算机数字猜谜游戏生成器的任务。
所以,
我的问题是如何确保randMIN始终低于randMAX?这些是猜测游戏边界的随机数字的名称。
答案 0 :(得分:1)
此方法将生成两个数字,其中randMIN
值始终低于randMAX
值:
import java.util.Random;
public class RandomMinMax
{
public static void main(String[] args)
{
Random random = new Random();
//Set range (minimum and maximum values).
int min = 5;
int max = 20;
//Get a random value between the (min) and (max-1) values and assign it to randMIN.
//In this example, randMIN will take any value between 5 and 19.
int randMIN = min + random.nextInt(max - min);
//The randMAX value will be a number generated between the (randMIN+1) and (max) values.
//In this example, if randMIN is 14, then randMAX will take any value between 15 and 20.
int randMAX = randMIN + 1 + random.nextInt(max - randMIN);
//Print the results.
System.out.println("randMIN: " + randMIN);
System.out.println("randMAX: " + randMAX);
}
}
答案 1 :(得分:-1)
如何在该范围内生成两个随机数。
完成后,检查哪一个更大,哪一个更小。
像:
Random rnd = new Random();
int randMin, randMax;
do {
int a = rnd.nextInt(randMax - randMin + 1) + randMin;
int b = rnd.nextInt(randMax - randMin + 1) + randMin;
if (a < b) {
randMin = a;
randMax = b;
} else if (a > b) {
randMin = b;
randMax = a;
}
// Repeat as long as there is no strict order
} while(randMin == randMax);
您还可以检查两个数字是否具有相同的值,并在这种情况下重新生成这些数字。
我希望这可以帮助你一点点。