网格使用循环

时间:2011-11-20 21:05:24

标签: java

我正在创建一个程序,用于创建一个由用户指定的行数和列数的网格。 我希望输出看起来像这样:

线(2..10)? 3

列(2..20)? 5

   |   |   |   |

---+---+---+---+---

   |   |   |   |

---+---+---+---+---

   |   |   |   |

但是我的程序改为:

线(2..10)? 3

列(2..20)? 5

   |   |   |   |

---+---+---+---+---

   |   |   |   |

---+---+---+---+---

   |   |   |   |

---+---+---+---+---

这就是程序的样子:

String[] vertical = new String[columns-1];
String[] horizontal = new String[columns];

do
{
    for(i = 0; i < vertical.length; ++i)
    {
        vertical[i] = ("   |");
        System.out.print(vertical[i]);
    }

    System.out.printf("%n");

    for(i = 1; i < columns; ++i)
    {
        horizontal[0] = ("---");
        horizontal[i] = ("+---");
    }

    if(horizontal.length > 0)
        System.out.print(horizontal[0]);

    for(int m = 1; m < horizontal.length; ++m)
        System.out.print(horizontal[m]);

    System.out.printf("%n");
    ++j;
} while (j <= lines - 1);

我知道我需要删除一条水平线,问题是我不知道该怎么做。抱歉格式不好。

1 个答案:

答案 0 :(得分:1)

在这里你去....而且是的,你的代码很可怕.....对不起,但是真实的事实

    String[] horizontal = new String[columns-1];
    String[] minusplus = new String[columns];

    int j = 0;

    for(int i = 1; i < columns; ++i)
        {
            minusplus[0] = ("---");
            minusplus[i] = ("+---");
        }

    for(int i = 0; i < horizontal.length; ++i)
        {
            horizontal[i] = ("   |");
        }

    do
    {
        for(int i = 0; i < horizontal.length; ++i)
        {
            System.out.print(horizontal[i]);
        }

        System.out.printf("%n");


        if ( j < lines - 1 ){
        for(int m = 0; m < minusplus.length; ++m)
            System.out.print(minusplus[m]);
        }

        System.out.printf("%n");

        ++j;
    } while ( j < lines);

编辑:在这里你有更好的实施方式:

int columns = 5;
int lines = 3;

    int j = 0;
    do {
        for (int i = 0; i < columns - 1; i++) {
            System.out.print("   |");
        }

        System.out.printf("%n");

        if (j < lines - 1) {

            System.out.print("---");
            for (int i = 1; i < columns; i++) {
                System.out.print("+---");
            }
        }
        System.out.printf("%n");

        ++j;
    } while (j < lines);
}