+ 2
How to generate a random number in Java?
Does anyone know how you can get a random number in Java? Or random ish, which is hard to predict?
4 Antworten
+ 11
/* There's an easy and simple way, just import the java.util.Random class and set the max and the lower limit implicitly */
import java.util.Random;
public class RandomNumbers
{
public static void main(String[] args) {
Random rand = new Random();
// 100 is the max limit, 1 is the min, modify it accordingly...
System.out.print(rand.nextInt(100)+1);
}
}
+ 5
👍
+ 3
Figured it out
//first need to import a java.util:
import java.util.concurrent.ThreadLocalRandom
//then you can make the int with a random number:
int randomNumber = ThreadLocalRandom.current().nextInt(min, max+1);
//this worked for me :)
+ 3
// edited ignore the other one 😁 //
import java.util.Random;
// main //
Random rnd = new Random();
int i [] = {1,2,3};
String z [] = {"a","b","c"};
int y = rnd.nextInt(i.length);
System.out.println( i[y]); //random int
System.out.println(z[y]); //random String