gpt4 book ai didi

java - 打印星号组成的 ASCII 菱形

转载 作者:行者123 更新时间:2023-11-30 09:17:06 28 4
gpt4 key购买 nike

我的程序打印出这样的钻石:

...............*
..........* * *
.....* * * * *
* * * * * * *
.....* * * * *
..........* * *
...............*

但它仅在参数或菱形的每一边为 4 时有效。例如,如果我输入 6,底部三角形的间距是错误的,我一直在努力弄清楚。

当参数改变时,底部的三角形不会改变,只有顶部的三角形会改变。它仅适用于输入 4

public static void printMoreStars(int n) {
int rowsPrime = 0;

for (int i = n + 1; i > 0; i--) {
for (int j = 0; j < (2 * i) - 1; j++) {
System.out.print(" ");
}
for (int d = 0; d < (2 * rowsPrime) - 1; d++) {
System.out.print("*" + " ");
}
System.out.println(); //new line character

rowsPrime += 1;
System.out.println(" ");
}

//bottom triangle
for (int i = 1; i < n + 1; i++) {
for (int j = 0; j < (2 * i) + 1; j++) {
System.out.print(" ");
}
for (int d = 0; d < rowsPrime; d++) {
System.out.print("*" + " ");
}
System.out.println(); //new line character

rowsPrime -= 2;
System.out.println(" ");
}
}

最佳答案

您在使用 rowPrimes 时犯了两个错误。请参阅下面的注释:

public class Stars {
public static void main(String[] args) {
printMoreStars(Integer.parseInt(args[0]));
}

public static void printMoreStars(int n) {
int rowsPrime = 0;

for (int i = n + 1; i > 0; i--) {
for (int j = 0; j < (2 * i) - 1; j++) {
System.out.print(" ");
}
for (int d = 0; d < (2 * rowsPrime) - 1; d++) {
System.out.print("*" + " ");
}
System.out.println(); //new line character

rowsPrime += 1;
System.out.println(" ");
}

rowsPrime -= 2; // <- middle line is already printed, so skip that

//bottom triangle
for (int i = 1; i < n + 1; i++) {
for (int j = 0; j < (2 * i) + 1; j++) {
System.out.print(" ");
}
for (int d = 0; d < (2 * rowsPrime) - 1; d++) { // <- changed condition to be the same as above
System.out.print("*" + " ");
}
System.out.println(); //new line character

rowsPrime--; // <- you have to decrease rowPrime by one.
System.out.println(" ");
}
}
}

关于java - 打印星号组成的 ASCII 菱形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19109066/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com