如何在Java中仅使用符号“*”来绘制图片?

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

我需要画这样的图:

         *
        ***
       *****
      *******
     *********
012345678901234567890123456789

在命令提示中,我需要输入两个值 Z 和 N。Z 表示绘图(第一行)的宽度,N 确定绘图的位置(从左侧开始)。为了完成所有这些,我需要使用多个字符串“0123456789”和一些数字来制作位置线。然后在这条线上方我需要有一个从数字 N 开始的第一行星号线。

我只到这里了:

public static void main(String[] args) {
    TODO Auto-generated method stub
    int Z = Integer.parseInt(args[0]);
    int N = Integer.parseInt(args[1]);
    String str = "*";
    System.out.println(str * 5);
}

但是程序输出错误:

The operator * is not defined for the argument type string.
我不知道如何定位这些线以便绘制图形。我知道我必须使用 for 循环。我的想法仅限于此:

System.out.println("*); System.out.println(ruler = "0123456789" * 3)

java
1个回答
0
投票

我认为你走在正确的道路上,也许你可能想考虑利用

String.repeat

import java.util.Scanner;

public class Main {
  private static final String POSITION_TEMPLATE = "0123456789";

  public static void main(String[] args) {
    try (Scanner scanner = new Scanner(System.in)) {
      System.out.print("Enter Z (width of first row): ");
      int z = scanner.nextInt();
      if (z < 1) {
        throw new IllegalArgumentException("Z must be greater than 0");
      }
      System.out.print("Enter N (position offset from left): ");
      int n = scanner.nextInt();
      if (n <= 0) {
        throw new IllegalArgumentException("N must be non-negative.");
      }
      printPyramid(n, z);
      String positionLine = generatePositionLine(n, z);
      System.out.println(positionLine);
    }
  }

  private static void printPyramid(int offset, int baseWidth) {
    for (int i = 0; i < baseWidth; i++) {
      int stars = 2 * i + 1;
      String line = " ".repeat(offset + baseWidth - i - 1) + "*".repeat(stars);
      System.out.println(line);
    }
  }

  private static String generatePositionLine(int offset, int width) {
    int totalLength = offset + 2 * width - 1;
    StringBuilder builder = new StringBuilder();
    while (builder.length() < totalLength + POSITION_TEMPLATE.length()) {
      builder.append(POSITION_TEMPLATE);
    }
    return builder.toString();
  }
}

用法示例:

Enter Z (width of first row): 7
Enter N (position offset from left): 5
           *
          ***
         *****
        *******
       *********
      ***********
     *************
012345678901234567890123456789

尝试godbolt.org

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