在Java中为1到50之间的循环中生成10个随机数



我需要在Java中创建一个程序,该程序在1到50之间生成10个随机数,并使用for循环输出它们。我已经弄清楚了如何生成随机数,但是无法弄清楚如何使用for循环来做到这一点。请帮助!

import java.util.Random;
class RandomNumbers
{
public static void main (String [] args)
{
int random = (int)(Math.random()* (50 + 1));
System.out.println (random);
}
}

只是将该代码放在这样的循环中:

for(int i=0;i<10;i++){
  int random = (int)(Math.random()* (50 + 1));
  System.out.println (random);
}

您正在成功创建一个随机数。您只需要循环10次获得10个不同的数字。

import java.util.Random;
class RandomNumbers {
    public static void main (String [] args)
    {
        for (int i=0; i<10;i++){
            int random = (int)(Math.random()* (50 + 1));
            System.out.println (random);
    }
}

每次生成新号码并将其打印出来时,请使用for-loop和loop 10次:

public static void main(String[] args) {
    for (int i = 0; i < 10; i++) {
        int random = (int)(Math.random() * (50 + 1));
        System.out.println(random);
    }
}

不是每句话的循环,而是使用随机

Random r = new Random();
long[] longs = r.longs(1, 50).limit(10).toArray();
Arrays.stream(longs).forEach(System.out::println);

1是包容性的,在这种情况下没有50个。

嵌套随机生成的数字和println for loop。

import java.util.Random;
class RandomNumbers
{
  public static void main (String[] args)
  {
    for (int i = 1 ; i <= 10 ; i++)
    {
      int random = (int) (Math.random () * (50 + 1));
      if (i < 10)
      {
        System.out.print (random + ", ");
      }
      else
      {
        System.out.print (random);
      }
    }
  }
}

关于我所做的更改的注释: println更改为打印,以便在同一行上输出所有十个数字,添加了输出格式化的if/else语句

您的输出应该看起来像这样:

35、27、39、19、7、48、19、27、8、38

最新更新