如何生成2个随机整数,然后进行比较?

huangapple go评论70阅读模式
英文:

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");

huangapple
  • 本文由 发表于 2020年10月16日 08:40:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/64381437.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定