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?
You can also use this way for getting random number between 1 and 100 as:
you wil get below error message
,known as type casting
if the true result is
Then you will get output as "0" because it is a integer data type.
output:2 because (100*0.02745=2.7456...etc)
you are importing
java.util
package. That's why its giving error. there is arandom()
injava.util
package too. Please remove the import statement importingjava.util
package. then your program will userandom()
method forjava.lang
by default and then your program will work. remember to cast it i.eCast abc to an integer.
As an alternative, if there's not a specific reason to use
Math.random()
, useRandom.nextInt()
: