简体   繁体   中英

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?

将 abc 转换为整数。

(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() :

import java.util.Random;

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 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 ie

int x = (int)(Math.random()*100);

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);
double  i = 2+Math.random()*100;
int j = (int)i;
System.out.print(j);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM