我需要画这样的图:
*
***
*****
*******
*********
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)
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