java-利用数组打印菱形

在for循环中,如果要使用到数组去打印一个简单的菱形,该怎么做?


public static void main(String[] args) 
{
      int n=5,c=0;
      String arr[]=new String[2*n-1];
      for(int i=1;i<=n;i++,c++)
      {
            arr[c]= new String(new char[n-i]).replace('\0', ' ');
            arr[c]+= new String(new char[2*i-1]).replace('\0', '*');
      }
      for(int i=n-1;i>0;i--,c++)
      {
            arr[c]= new String(new char[n-i]).replace('\0', ' ');
            arr[c]+= new String(new char[2*i-1]).replace('\0', '*');
      }
      for(int i=0;i<c;i++)
            System.out.println(arr[i]);
}

如果想打印菱形的话,你可以看看我的示例:

  1. 这是不使用 for 循环的
public class Main {

    public static void main(String[] args) {
        System.out.println("  *");
        System.out.println(" ***");
        System.out.println("*****");
        System.out.println(" ***");
        System.out.println("  *");
    }
}
  1. 这是使用 for 循环的
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        
        System.out.println("请输入菱形的长度:");
        Scanner in = new Scanner(System.in);
        int len = in.nextInt();
        if (len % 2 == 0) {
            len++; // 计算菱形大小
        }
        for (int i = 0; i < len / 2 + 1; i++) {
            for (int j = len / 2 + 1; j > i + 1; j--) {
                System.out.print(" "); // 输出左上角位置的空白
            }
            for (int j = 0; j < 2 * i + 1; j++) {
                System.out.print("*"); // 输出菱形上半部边缘
            }
            System.out.println(); // 换行
        }
        for (int i = len / 2 + 1; i < len; i++) {
            for (int j = 0; j < i - len / 2; j++) {
                System.out.print(" "); // 输出菱形左下角空白
            }
            for (int j = 0; j < 2 * len - 1 - 2 * i; j++) {
                System.out.print("*"); // 输出菱形下半部边缘
            }
            System.out.println(); // 换行
        }
    }

}