aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes random numbers Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "random numbers" Watch "random numbers" New topic
Author

random numbers

simon kumar
Greenhorn

Joined: Feb 06, 2002
Posts: 13
Hi,
what could be the ans for the following qs..
Which of the following will output a random with values only from 1 to 10?
1) System.out.println(Math.round(Math.random()* 10));
2) System.out.println(Math.round(Math.random() % 10));
3) System.out.println(Math.random() *10);
4) None of the above
i feel it should be (1) and (3)..
plz verify it..
simon
Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610
simon, why don't you compile and run the code and see how it works... What does Math.random do? What does Math.round do? You have to ask yourself those questions...
in the third case, a double is returned which is probably not what we want (between 1 and 10 not 1.0 and 10.0)...
HIH


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
Originally posted by simon kumar:
Hi,
what could be the ans for the following qs..
Which of the following will output a random with values only from 1 to 10?
1) System.out.println(Math.round(Math.random()* 10));
2) System.out.println(Math.round(Math.random() % 10));
3) System.out.println(Math.random() *10);
4) None of the above
i feel it should be (1) and (3)..
plz verify it..
simon

Actually, I'm not so sure if any of them will work. Valentin's right - you should try this code out for yourself and see what it does - that's whay I just did.
I was right - none of them work. The answer is, which one's will give a value between 1 and 10. (You should also know if this is exclusive or inclusive.) However, the closest ones are the first and third. Unfortunately, both of them can give values that are less than 1 because Math.random() can return a value from 0.0 to 1.0. Take a look - I'm sure you'll find this to be the case.
If you really want to get a value between 1 and 10 (I'll do inclusive), you'll need to do something like this:

Try and figure it out and, if you can't let me know and I'll explain further.
Corey


SCJP Tipline, etc.
Rob Ross
Bartender

Joined: Jan 07, 2002
Posts: 2205
<nodding head> yup, I agree with Corey. None of the statements given as answers will produce the requested output. So the answer to the original test question is "none of the above."
Actually, you don't need the call to Math.round().
You can just do
(int)(Math.random()*9+1)
[ February 12, 2002: Message edited by: Rob Ross ]

Rob
SCJP 1.4
 
Don't get me started about those stupid light bulbs.
 
subject: random numbers