Question Locked

Java Query

0 helpful
2 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

I have an exam this week in college. One of the past MCQ questions is:-

"What is the purpose of (int) in the statement
1 + (int) (Math.random() * 8)"

Any ideas on what the purpose of (int) is here.
Sound.

2 replies

by absolutely

http://java.about.com/library/weekly/aa_random_num.htm

[b]Generate Random Integers[/b]

If one actually needs an [b]int[/b] instead of a [b]double[/b], simply convert the returned [b]double[/b] to an [b]int[/b] by casting it.

int randomInt = 1 + (int)(Math.random() * 50);

This will truncate the generated [b]double[/b] and return an [b]int between 1 and 50. I got "19." Don't forget the parentheses around the Math.random() * 50. This is required, otherwise the [b]double[/b] will be truncated before the multiplication operation!

This discussion is closed to new replies.