File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Help rqrd with math class and boolean expression Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Help rqrd with math class and boolean expression" Watch "Help rqrd with math class and boolean expression" New topic
Author

Help rqrd with math class and boolean expression

Sonaina Kolachi
Greenhorn

Joined: Jul 29, 2001
Posts: 2
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
kyle amburn
Ranch Hand

Joined: Jul 29, 2001
Posts: 64
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
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.
kyle amburn
Ranch Hand

Joined: Jul 29, 2001
Posts: 64
You got it.
Kyle
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Help rqrd with math class and boolean expression
 
Similar Threads
Head First Java problem
Slower When threaded.
Issues with the setting up of Actionlisteners for JButtons
Whiz lab Prep kit PRoblems
Threading question