aspose file tools*
The moose likes Beginning Java and the fly likes Primitive int to Integer conversion. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Primitive int to Integer conversion." Watch "Primitive int to Integer conversion." New topic
Author

Primitive int to Integer conversion.

Melanie Miller
Greenhorn

Joined: Jul 24, 2002
Posts: 13
What do I have to do to convert from primitive int
to Integer types?
I have this statement and it's always returning zeroes.
Integer value;
value = new Integer ( (int) Math.random() * 100);
yet, value is always zero.
What am I doing wrong here?
This worked when I stored it back into an int array but not when I convert it to type Integer.
Hashtable needs it to be in type Integer.
Please send help.
Thanks.
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
I believe (int)Math.random() is resulting in 0. Do you not mean (int)(Math.random()*100) ?


Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Kathy Sierra
Cowgirl and Author
Ranch Hand

Joined: Oct 10, 2002
Posts: 1572
Howdy --
I think you just need to add the parens, so that you have:
(int) (Math.random() * 100);
Rather than:
(int) Math.random() * 100;
Without the parens around the whole thing, the (int) cast applies ONLY to the Math.random(), which -- as Barry said -- always returns an int value of 0. Then you are simply multiplying 100 x 0 each time. So you want the cast to apply to the whole expression, rather than just the return value of random().
cheers
Kathy
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Primitive int to Integer conversion.