Java:使用 If-Else 语句为网格列着色

Java: Coloring Grid Columns with If-Else Statements

我一直在尝试将某些列设置为某些颜色,但没有得到正确的结果。我对其中的大部分感到有些困惑。

如有任何帮助,我将不胜感激!

我想要完成的事情:

使用一系列 if - else 语句使第 4 列为绿色,第 5 列为蓝色,第 6 列为红色,其余为黄色。

我的(不正确的)代码:

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      
            }
        }
    }
}

它应该是什么样子:(我用油漆来表示)

我得到的(错误的):

您有 4 种情况需要考虑:

  1. x==4,绿色
  2. x==5,蓝色
  3. x==6,红色
  4. 其他,黄色

但是你的第三个 if 语句实现了 if x==6 red else yellow,所以即使一个列已经被前面的 if 设置为绿色或蓝色,它也会被重新此处设置为黄色。

可以用else if解决问题:

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);
}

在您当前的代码中,每次 x != 6 都会应用最后一个 else 语句,导致该行变为黄色。