This is the coding of the program I wrote. public class GetValue{ public static void main(String[]args){ int a=(int)Math.random()*500; int b=(int)Math.random()*700;
if(a<b){<br /> System.out.println("TRUE");<br /> }<br /> if(a>b){ System.out.println("UNDECIDED"); } if(a==b){ System.out.println("FALSE"); } } } The compiler keeps giving me FALSE and never the other answer. Could someone explain why? SK
Hi- Check the precedence rules. The cast to an int is being applied to the double value before being multiplied. Since a (int) cast truncates the double value (which is always between 0.0 and 1.0) unless if the random number is 1.0, the cast value will always be 0. You need to put parentheses around the multiplication. See the following adjusted code. public class GetValue{ public static void main(String[]args){ int a=(int)(Math.random()*500); int b=(int)(Math.random()*700); if(a <b){<br /> System.out.println("TRUE");<br /> }<br /> if(a>b){ System.out.println("UNDECIDED"); } if(a==b){ System.out.println("FALSE"); } } }
Kyle
[This message has been edited by kyle amburn (edited August 05, 2001).]
Sonaina Kolachi
Greenhorn
Joined: Jul 29, 2001
Posts: 2
posted
0
Thanx KYLE, This was a big help. NOw I understand that the random value was being casted as an integer before being multiplied by the constants, is that it? And the answer with the previous code was always zero that is why the compiler kept giving me "False" only. I have compiled and run the new code and it is giving the rqrd result. Once again thanx SK.