打印星号的 ASCII 菱形 [英] Print an ASCII diamond of asterisks
本文介绍了打印星号的 ASCII 菱形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的程序打印出这样的钻石:
My program that prints out a diamond like this:
...............*
..........* * *
.....* * * * *
* * * * * * *
.....* * * * *
..........* * *
...............*
但它仅在参数或菱形的每一侧为 4
时才有效.例如,如果我输入6
,底部三角形的间距是错误的,我正在尝试解决.
But it only works if the parameter or each side of the diamond is 4
. For example if I input 6
, the spacing on the bottom triangle is wrong and I been trying to figure it out.
当参数改变时,底部的三角形不会改变,只有顶部的三角形会改变.它仅适用于输入 4
.
The bottom triangle doesn't change when the parameter is changed, only the top one does. It only works for input 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
时犯了两个错误.请参阅下面的注释:
You made two mistakes when using rowPrimes
. See my annotations below:
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(" ");
}
}
}
这篇关于打印星号的 ASCII 菱形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文