How do you use Math.random to generate random ints?
My code is:
int abc= (Math.random()*100);
System.out.println(abc);
All it prints out is 0, how can I fix this?
How do you use Math.random to generate random ints?
My code is:
int abc= (Math.random()*100);
System.out.println(abc);
All it prints out is 0, how can I fix this?
Cast abc to an integer.
(int)(Math.random()*100);
For your code to compile you need to cast the result to an int.
int abc = (int) (Math.random() * 100);
However, if you instead use the java.util.Random class it has built in method for you
Random random = new Random();
int abc = random.nextInt(100);
As an alternative, if there's not a specific reason to use Math.random()
, use Random.nextInt()
:
Random rnd = new Random();
int abc = rnd.nextInt(100); // +1 if you want 1-100, otherwise will be 0-99.
int abc= (Math.random()*100);// wrong
you wil get below error message
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from double to int
int abc= (int) (Math.random()*100);// add "(int)" data type
,known as type casting
if the true result is
int abc= (int) (Math.random()*1)=0.027475
Then you will get output as "0" because it is a integer data type.
int abc= (int) (Math.random()*100)=0.02745
output:2 because (100*0.02745=2.7456...etc)
You can also use this way for getting random number between 1 and 100 as:
SecureRandom src=new SecureRandom();
int random=1 + src.nextInt(100);
you are importing java.util
package. That's why its giving error. there is a random()
in java.util
package too. Please remove the import statement importing java.util
package. then your program will use random()
method for java.lang
by default and then your program will work. remember to cast it i.e
int x = (int)(Math.random()*100);
double i = 2+Math.random()*100;
int j = (int)i;
System.out.print(j);