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

问题描述 投票:0回答:2

鉴于:

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

如何修改代码来打印边长 = 3 的正方形?

[][][]
[][][]
[][][]
java loops for-loop
2个回答
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();
    }
}

0
投票


public class SquarPattern {

public static void main(String[] args) {

    int n = 6;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if((i==0 || i==n-1 )  || (j==0 || j==n-1)) {
              System.out.print("*");
            }else {
                  System.out.print(" ");
            }
        }
        System.out.println();
    }

}

}

© www.soinside.com 2019 - 2024. All rights reserved.