Reputation: 1
I am trying to write a program that draws a square 200 pixels by 200 pixels, square with colors red (red value 255), green (green value 255), blue (blue value 255) and magenta (red value 255 and blue value 255). All other RGB values are set to 0. However, my code has a bug, and produces a rather yellow, green, Magenta and Blue. How do I get the Red colour instead the yellow? Below is my code.
var img = new SimpleImage(200,200);
for (var px of img.values()){
var x = px.getX();
var y = px.getY();
if (x < img.getWidth()/2){
px.setRed(255);
}
if (y>img.getHeight()/2){
px.setBlue(255);
}
else {
px.setGreen(255);
}
}
print (img);
Upvotes: 0
Views: 701
Reputation: 24988
Walk through the program and consider how it will be executed if, say, x = 50, y = 50
x < img.getWidth()/2
evaluates to true so red is set to 255, proceed to next statement
y > img.getHeight()/2
evaluates to false, so the "else" code is executed and green is set to 255
That gives you a pixel with 255 red and 255 green, rather than what you expect.
If you use elseif
you'll have the desired behaviour.
Upvotes: 1