+ 2

How to randomize values in Java?

I`d be happy if you can tell me the sintax.

27th Nov 2016, 12:19 AM
Silas Junior
Silas Junior - avatar
3 Antworten
+ 7
You could import the Random class.. import java.util.Random; Then from there you would have to create an instance of that class. So something like.. Random rand = new Random(); Then you would call on the random object you created and use dot notation to use the method 'nextInt'. int someNumber = rand.nextInt(); Of course you would pass in an argument into the nextInt method.
27th Nov 2016, 12:49 AM
Don
Don - avatar
+ 5
you can also use Math.random(); this will generate a random value in the range [0, 1) so if you want to generate a number in a given min, max range just do: int min = 120; int max = 150; double randVal = Math.random()*(max - min) + min; System.out.println((int)randVal); edit use double since the returned value is double if you want an integer, simple cast it (int)randVal
27th Nov 2016, 6:49 AM
Burey
Burey - avatar
+ 2
Hey Don! Thank you, man
27th Nov 2016, 2:28 AM
Silas Junior
Silas Junior - avatar