简体   繁体   中英

Generating random numbers in Java?

I would like to ask how to make a program that needs using a loop to generate 100 different numbers from 200 to 500 and then multiply them all together. The result should be printed on the console. I don't know how to multiply all numbers together.

This is what I did so far:

import java.util.Random;

public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        for(int i=0;i<100;i++)
            System.out.println("Random number["+(i+1)+"]:"+(int)(Math.random()*500));
    } 
}

I believe you are looking for something like,

Random rand = new Random();
BigInteger val = BigInteger.ONE;
for (int i = 0; i < 100; i++) {
    int v = rand.nextInt(301) + 200; // 0-300 + 200, is the range 200-500.
    val = val.multiply(BigInteger.valueOf(v));
    System.out.printf("Random number %d: %d%n", i + 1, v);
}
System.out.println(val);

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