Java Query
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.
Software
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.
by s.kelly Accepted solution
by absolutely Accepted solution
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.
Sort by Trending