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

15

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 tagged with java random

~ Asked on 2011-12-22 22:54:16

The Best Answer is


25

Cast abc to an integer.

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

~ Answered on 2011-12-22 22:55:17


20

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

~ Answered on 2011-12-22 23:01:01


Most Viewed Questions: