Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# colors in life!!!! :)

ankush walia
Ranch Hand
Posts: 95
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!!

ryan burgdorfer
Ranch Hand
Posts: 219
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

Nathan Pruett
Bartender
Posts: 4121
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 :

HTH,
-Nate

ryan burgdorfer
Ranch Hand
Posts: 219
oh yeah, I did forget those parentheses, didn't I...
Operator precedence bites me in the butt often, I gotta watch that
~Ryan

Randall Twede
Ranch Hand
Posts: 4683
8
I use parenthesis even if I dont have to because it makes the code easier to understand.

 Did you see how Paul cut 87% off of his electric heat bill with 82 watts of micro heaters?