How do you use math.random to generate random ints?

后端 未结 7 895
情话喂你
情话喂你 2020-12-06 01:23

How do you use Math.random to generate random ints?

My code is:

int abc= (Math.random()*100);
System.out.println(abc);

All it print

7条回答
  •  不知归路
    2020-12-06 01:42

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

提交回复
热议问题