How to generate a random number in Java? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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?

22nd Aug 2017, 5:25 PM
Zachosekken
Zachosekken - avatar
4 Answers
+ 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); } }
22nd Aug 2017, 5:42 PM
Dev
Dev - avatar
+ 5
👍
22nd Aug 2017, 5:43 PM
Manual
Manual - avatar
+ 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 :)
22nd Aug 2017, 5:31 PM
Zachosekken
Zachosekken - avatar
+ 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
22nd Aug 2017, 6:10 PM
D_Stark
D_Stark - avatar