Aramza Aramza - 1 month ago 13
Java Question

Java: Drawing with if-else statements

I am having trouble getting if-else statement to draw correct colors for my program. I'm under the impression that the if-statements are not organized correctly with the else statement and the "setColor," I am stumped on how to make the black render as yellow. The best way to describe it is to show it.

I'd appreciate any help!

My output (wrong):

Wrong output

Goal output (right):

enter image description here

My code:

import java.awt.*;

public class IfGridEx3 {
public static void main(String[] args) {
DrawingPanel panel = new DrawingPanel(400, 400);
panel.setBackground(Color.blue);
Graphics g = panel.getGraphics();

int sizeX = 40;
int sizeY = 40;
for (int x = 0; x < 10; x++) {
for (int y = 0; y < 10; y++) {
int cornerX = x*sizeX;
int cornerY = y*sizeY;

if (x > 1)
if (x < 8)
if (y > 1)
if (y < 8)
g.setColor(Color.green);
else
g.setColor(Color.yellow);


g.fillRect(cornerX+1, cornerY+1, sizeX-2, sizeY-2);
g.setColor(Color.black);
g.drawString("x="+x, cornerX+10, cornerY+15); // text is positioned at its baseline
g.drawString("y="+y, cornerX+10, cornerY+33); // offsets from the corner do centering
}
}
}

}

Answer

Your else is based only on result of last if, so g.setColor(Color.yellow); will be invoked only if all conditions

            if (x > 1)
                if (x < 8)
                    if (y > 1)

will be true (otherwise condition in last if will not even be tested),
and result evaluation of condition from last if

                        if (y < 8)

will be false. It means, that else will not be invoked if previous 3 conditions are false, which is why you are seeing some areas unset.

To solve this problem you can create single condition for center area

if (x > 1 && x < 8 && y > 1 && y < 8){
    g.setColor(Color.green);
} else {
    g.setColor(Color.yellow);
}