英文:
how would I produce 2 random integers, and then compare them?
问题
我想使用java.util.random生成两个不同的随机整数。然后想要比较这两个数字,例如代码生成了5和9。然后,如果一个数字大于另一个数字,使用条件运算符将较大的数字放入变量var1。最终结果是"9是较大的数字"。我刚开始学,目前只有这些代码。
Random rand = new Random();
int n = rand.nextInt(50);
n += 1;
System.out.println(n);
我需要创建n1和n2吗?还是可以从同一个变量生成2个随机数字?
英文:
I want to produce 2 different random integers using java.util.random. then want to compare those two numbers, for example the code produces 5 and 9. then if one number is bigger than the other, use conditional operators to put the bigger number into variable var1. end result "9 is the bigger number". this is all I have starting out.
Random rand = new Random();
int n = rand.nextInt(50);
n += 1;
System.out.println(n);
do I have to create n1 and n2 or can I produce 2 random numbers from the same variable?
答案1
得分: 2
不确定为什么您要以这种方式进行,但您可以像这样操作:
Random rand = new Random();
int var1 = Math.max(rand.nextInt(50), rand.nextInt(50));
System.out.println(var1 + "是较大的数字");
英文:
Not sure why do you even want to do this that way, but you can do it like this:
Random rand = new Random();
int var1 = Math.max(rand.nextInt(50), rand.nextInt(50));
System.out.println(var1 + " is the bigger number");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论