Java程序使用for循环绘制一个正方形?

时间:2015-01-11 12:01:53

标签: java loops for-loop

假设:

public static void printTriangle(int sideLength) 
{
    for (int i = 0; i <= sideLength; i++) {
        for (int j = 0; j < i; j++){
            System.out.print("[]");
        }
        System.out.println();
    }
}

如何修改代码以打印sideLength = 3的方块?

[][][]
[][][]
[][][]

1 个答案:

答案 0 :(得分:5)

像这样:

public static void printSquare(int sideLength) 
{
    for (int i = 0; i < sideLength; i++) {
        for (int j = 0; j < sideLength; j++) {
            System.out.print("[]");
        }
        System.out.println();
    }
}