[java] How do you use math.random to generate random ints?

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?

This question is related to java random

The answer is


As an alternative, if there's not a specific reason to use Math.random(), use Random.nextInt():

import java.util.Random;

Random rnd = new Random();
int abc = rnd.nextInt(100); // +1 if you want 1-100, otherwise will be 0-99.

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);

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)


double  i = 2+Math.random()*100;
int j = (int)i;
System.out.print(j);

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);

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);