+ 4
How to generate random integers within a specific range in Java?
How do I generate a random int value in a specific range? I have tried the following, but those do not work:
5 odpowiedzi
+ 4
Yah
+ 3
just noting, Satish Kumar 's code would generate a random number from 0 to 9.
you can also use the Math.random() function without needing to import anything. It generates a random number between 0-.9999...
(int) Math.random()*11 would give an integer from 0-10
+ 3
(int)(Math.random() * 10) //Random int from 0 to 9
(int)(Math.random() * 10) + 1 //Random int from 1 to 10
+ 2
import java.util.Random;
class Demo{
public static void main(String[] args){
Random r=new Random();
int i=r.nextInt(10);
System.out.print(i);
}
}
You can specify the range at the place of 10