True. Even then, this is probably not the code he really wants. Instead of using casts on a Random method returning doubles, he could use the java.lang.util.Random.nextInt() method to get an integer in the range he specifies.
Then instead of "(int( (Math.random()*9)+1" he could have, after a declaration like "Random mRandGen = new Random();", mRandGen.nextInt(9) +1; to return a random integer from 1 to 10. Code w/o casts is generally better than code with casts. Unless, of course, it resorts to drastic contortions to avoid the case. But such is not the case here., On Nov 19, 11:10 pm, Lance Nanek <lna...@gmail.com> wrote: > The value of this expression will always be zero: > (int) Math.random() > > Casting to an integer removes the fractional portion. Casting has a > higher operator precedence than multiplication or addition, so happens > first in your full expression. Parentheses could be used to alter when > the cast happens, however. Like this: > (int) (Math.random() * 9) + 1 > > On Nov 18, 11:00 am, Jags <jag...@gmail.com> wrote: > > > I am fairly new to android and java > > > i tried following code to generate different random numbers in the > > ranges of 1 - 9 > > > i wrote following code > > > int i = (int) Math.random() * 9 + 1; > > while (i == previousIndex) { > > i = (int) Math.random() * 9 + 1; > > } > > > always i is getting 0 and goes to infinite loop, why so ? > > > sorry for a novice question though :P -- You received this message because you are subscribed to the Google Groups "Android Beginners" group. To post to this group, send email to android-beginners@googlegroups.com To unsubscribe from this group, send email to android-beginners+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/android-beginners?hl=en