Andrew Andrew - 2 months ago 8
Java Question

Java: Coloring Grid Columns with If-Else Statements

I have been tinkering with setting certain columns to certain colors with no correct outcome. I am somewhat stumped on the majority of it.

I'd appreciate any help!

What I'm attempting to accomplish:

Use a series of if - else statements to make column 4 green, column 5 blue, column 6 red, and leave the rest yellow.

My (incorrect) Code:

import java.awt.*;

public class IfGrid
{
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 == 4){ // If Statements start here
g.setColor(Color.green); }
if (x == 5) {
g.setColor(Color.blue); }
if (x == 6) {
g.setColor(Color.red); }
else {
g.setColor(Color.yellow); }

g.fillRect(cornerX, cornerY, sizeX-1, sizeY-1);
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
}
}
}
}


What it should look like: (I used paint to indicate)

Correct Picture Example

What I get (Wrong):

Wrong Output

Answer

You can use else if to solve the problem:

if (x == 4) {
  g.setColor(Color.green); 
} else if (x == 5) {
  g.setColor(Color.blue); 
} else if (x == 6) {
  g.setColor(Color.red);
} else {
  g.setColor(Color.yellow);
}

In your current code, the last else statement was being applied every time that x != 6, causing the line to become yellow.