This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
hi everyone; can anyone how random numbers are used to generate the different colours(selecting from Red,Green & Blue)!!i want to know how the random function works in this respect and what all functions can be performed with these colours!! <----- SKY_IS_THE_LIMIT------> ankush!!
Ankush, The Color class has many different constructors. The two which are easiest to use are Color( int r, int g, int b) where r, g, and b are ints in the range 0-255, and Color( float r, float g, float b) where r, g, and b are floats in the range 0.0-1.0. Using the Math.random() function, you could either say: int x = ( int )Math.random() * 255; int y = ( int )Math.random() * 255; int z = ( int )Math.random() * 255; Color randomColor = new Color( x, y, z ); // or... float x = ( float )Math.random(); float y = ( float )Math.random(); float z = ( float )Math.random(); Color randomColor = new Color( x, y, z ); Note that in either case, you have to cast the value produced by Math.random() to the desired value, since it normally produces a double greater than or equal to 0.0 and less than 1.0. Hope this helps... ~Ryan
Just remember if you use the 'int' version... random() returns a double value in the range 0>=x<1... If you cast this to an int it will always return 0... Make sure you cast the result of the multiplication to prevent this :
Write once, run anywhere, because there's nowhere to hide! - /. A.C.
Joined: Jan 24, 2001
oh yeah, I did forget those parentheses, didn't I... Operator precedence bites me in the butt often, I gotta watch that ~Ryan