File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Primitive int to Integer conversion." Watch "Primitive int to Integer conversion." New topic

Primitive int to Integer conversion.

Melanie Miller

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.
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

Joined: Oct 10, 2002
Posts: 1589
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().
It is sorta covered in the JavaRanch Style Guide.
subject: Primitive int to Integer conversion.
It's not a secret anymore!