简体   繁体   English

Java:绘制乘法表的起始循环增量

[英]Java: Starting loop increment for drawing a multiplication table

I am having trouble figuring out how to remove the 0's in this table. 我无法弄清楚如何删除此表中的0。 I've attempted looking it up online and have had little success figuring it out that way (probably not searching it correctly). 我试图在网上查找它并没有成功找到它(可能没有正确搜索)。 I am attempting to get Figure #1 to appear like Figure #2 besides a few stylistic changes. 我试图让图#1看起来像图#2,除了一些风格上的变化。

I'd appreciate any help. 我很感激任何帮助。

Code: ( http://www.buildingjavaprograms.com/DrawingPanel.java ) Drawing Panel Used 代码:( http://www.buildingjavaprograms.com/DrawingPanel.java )使用绘图面板

import java.awt.*;

public class IfGridFor {
    public static void main(String[] args) {
        DrawingPanel panel = new DrawingPanel(400, 520);
        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 <= 12; y++) {               
                int cornerX = x*sizeX;
                int cornerY = y*sizeY;

                if ((x + y) % 2 == 0)
                    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  + " * " + y, cornerX + 5, cornerY + 15); // text is
                g.drawString("= " + x * y, cornerX + 5, cornerY + 33); // offsets
            }
        }
    }
}

Figure #1: 图1:

图1

Figure #2: 图#2:

图#2

You are almost done - all you need is changing what gets shown from x , y , x*y to (x+1) , (y+1) , (x+1)*(y+1) , and reducing the height of the panel by one row: 你差不多完成了 - 你所需要的只是改变从xyx*y(x+1)(y+1)(x+1)*(y+1) ,并降低高度小组的一行:

DrawingPanel panel = new DrawingPanel(400, 480); // 12 rows, not 13
...
for (int x = 0; x < 10; x++) {
    for (int y = 0; y < 12; y++) {  // < instead of <=
        ...
        g.drawString((x+1)  + " * " + (y+1), cornerX + 5, cornerY + 15); // text is
        g.drawString("" + (x+1) * (y+1), cornerX + 5, cornerY + 33); // offsets
    }
}

The rest of your code (ie the ... parts) remain the same. 其余代码(即...部分)保持不变。

If I'm understanding your question correctly, you want to remove the top row and the left column? 如果我正确理解您的问题,您想删除顶行和左列吗? If so, start your for loops at one instead of zero. 如果是这样,请在一个而不是零处启动for循环。 Also your outer loop should have the condition x <= 10 if you want the figure to include the square labelled '10'. 如果您希望图形包含标记为“10”的方形,则外部循环应具有条件x <= 10

Then change the lines: 然后改变线条:

int cornerX = x*sizeX;
int cornerY = y*sizeY; 

to: 至:

int cornerX = (x-1)*sizeX;
int cornerY = (y-1)*sizeY;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM