+ 2
How to randomize values in Java?
I`d be happy if you can tell me the sintax.
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.
+ 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
+ 2
Hey Don! Thank you, man