How do you use math.random to generate random ints

2019-01-18 11:38发布

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?

标签: java random
7条回答
爷的心禁止访问
2楼-- · 2019-01-18 11:53

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);
查看更多
虎瘦雄心在
3楼-- · 2019-01-18 11:56
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)

查看更多
趁早两清
4楼-- · 2019-01-18 11:58

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);
查看更多
Root(大扎)
5楼-- · 2019-01-18 12:04

Cast abc to an integer.

(int)(Math.random()*100);
查看更多
时光不老,我们不散
6楼-- · 2019-01-18 12:06

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.
查看更多
一夜七次
7楼-- · 2019-01-18 12:08
double  i = 2+Math.random()*100;
int j = (int)i;
System.out.print(j);
查看更多
登录 后发表回答