简体   繁体   中英

Using math.random to generate a certain amount of random numbers in java

I need help making a program in java that lets you write a number in textField and then generate that amount of random numbers from 0-9 using i = (int) (Math.random() * 10.0). For example if I would write 5 in the textField the program would generate 5 random numbers from 0-9.

Thanks

Using the new Java 8 streams API:

int n = Integer.parseInt(myTextField.getText());
int[] random = ThreadLocalRandom.current().ints(0, 10).limit(n).toArray();
  • uses the current thread local random (recommended over creating a new Random instance)
  • creates a random stream of integers in the range [0..10) -> 0..9
  • Stream terminates after n numbers have been generated
  • the stream result is collected and returned as an array
int x = value entered in textfield;
int generatedRandomNumber = 0;
java.util.Random rand = new java.util.Random();
for(int i=0 ; i<x ; i++) {
    generatedRandomNumber=rand.nextInt(10);//here you have your random number, do whatever you want....
}

Ok since you want to use the Math.random() method try the following:

    int times = 5;//how many numbers to output

    for(int i = 0; i < times; i++)
    {
        System.out.println((int)(Math.random()*10));
        //you must cast the output of Math.random() to int since it returns double values
    }

I multiplied by 10 because Math.random() returns a value greater than or equal to 0.0 and less than 1.0.

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