简体   繁体   中英

Generating 10 random numbers in a for loop between 1 and 50 in java

I need to create a program in Java which generates 10 random numbers between 1 to 50 and output them using a for loop. I have figured out how to generate the random numbers, but cant figure out how to do it using a for loop. Please help!

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

Just put that code in a for loop like this:

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

You are successfully creating one random number. You just have to loop this 10times to get 10 different numbers.

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

Use a for-loop and loop 10 times, every time generating a new number and printing it out:

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

Not in a for loop per say, but usesRandom

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

1 is inclusive and 50 is not in this case.

Nest your randomly generated number and println in a 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);
      }
    }
  }
}

Notes on changes I made: println changed to print so that all ten numbers are output on the same line, added the if/else statement for output formatting

Your output should look like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM