• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

colors in life!!!! :)

 
ankush walia
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 4439
3
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I use parenthesis even if I dont have to because it makes the code easier to understand.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic