3

I am trying to fill the whole screen with squares, each one filled with a different color. I am able to generate the entire screen full of squares, but I cannot get them to be a random color. Here is what I have so far:

import java.util.Random;

public class RGBRandom
{
  public static void main(String[] args)
{
StdDraw.setScale(0, 100);

for (int x = 0; x <= 100; x++)
{     
  for (int y = 0; y <= 100; y++)
  {
    int r = (int)Math.random()*256;

    int g = (int)Math.random()*256;

    int b = (int)Math.random()*256;

    StdDraw.setPenColor(r, g, b);
    StdDraw.filledSquare(x, y, 0.5);
  }
} 
}
}
inda1
  • 63
  • 1
  • 10

2 Answers2

5

The expression Math.random() generates a real number between 0 and 1 (not including 1). Your cast to an (int) effectively converts it to 0. You need brackets around the whole expression so that the cast to an int comes after you have multiplied the random number by 256.

E.g.

int r = (int) (Math.random() * 256);

Or, as Nichar suggests, use Random instead:

Random random = new Random();

...

int r = random.nextInt(256);
int g = random.nextInt(256);
int b = random.nextInt(256);

The random.nextInt(256) will give you a random number between 0 and 255 (inclusive). It would be better to create the instance of Random outside of the loops.

ᴇʟᴇvᴀтᴇ
  • 12,285
  • 4
  • 43
  • 66
1

Better use nextInt(), so it would look like this:

int randomNum = rand.nextInt(255)+1;
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183