Aramza
Aramza

Reputation: 193

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

Upvotes: 0

Views: 573

Answers (2)

Mike Laren
Mike Laren

Reputation: 8178

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.

Upvotes: 2

Scott Hunter
Scott Hunter

Reputation: 49803

You have 4 cases to consider:

  1. x==4, green
  2. x==5, blue
  3. x==6, red
  4. anything else, yellow

But your third if statement implements if x==6 red else yellow, so even if a column has been set to green or blue by a previous if, it will be re-set to yellow here.

Upvotes: 1

Related Questions