Search code examples
javafor-loopdrawingincrementmultiplication

Java: Starting loop increment for drawing a multiplication table


I am having trouble figuring out how to remove the 0's in this table. 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.

I'd appreciate any help.

Code: (http://www.buildingjavaprograms.com/DrawingPanel.java) Drawing Panel Used

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:

Figure #1

Figure #2:

Figure #2


Solution

  • 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:

    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 (i.e. the ... parts) remain the same.