Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Primitive int to Integer conversion.

 
Melanie Miller
Greenhorn
Posts: 13
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7729
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I believe (int)Math.random() is resulting in 0. Do you not mean (int)(Math.random()*100) ?
 
Kathy Sierra
Cowgirl and Author
Rancher
Posts: 1589
5
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic