【发布时间】:2015-10-01 13:34:11
【问题描述】:
我在打印填充钻石时遇到了一些问题。程序错误地格式化了菱形。
这段代码:
for (rows = 1; rows < height; rows += 2){
for (spaces =0; spaces < height - 1 - rows / 2; spaces++){
System.out.print(" ");
}
for (stars = 0; stars < rows; stars++){
System.out.println("*");
}
}
打印出来:
Please enter a positive odd height for the diamond:
9
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
编辑:我已经完成了钻石的上半部分,但我似乎无法将下半部分放下。它创建了一个无限循环。
for (rows = 1; rows < height + 1 ; rows += 2){
for (spaces =0; spaces < height - 1 - rows / 2; spaces++){
System.out.print(" ");
}
for (stars = 0; stars < rows; stars++){
System.out.print("*");
}
System.out.println("");
}
for (rows = 1; rows < height; rows -= 2){
for (spaces =0; spaces < height; spaces++){
System.out.print(" ");
}
for (stars = 0; stars < rows; stars++){
System.out.print("*");
}
System.out.println("");
}
编辑 2:修复了无限循环,但现在星星未对齐:
for (rows = 1; rows < height + 1 ; rows += 2){
for (spaces =0; spaces < height - 1 - rows / 2; spaces++){
System.out.print(" ");
}
for (stars = 0; stars < rows; stars++){
System.out.print("*");
}
System.out.println("");
}
for (rows = height - 2; rows >= 1; rows -= 2){
for (spaces =0; spaces < height; spaces++){
System.out.print(" ");
}
for (stars = 0; stars < rows; stars++){
System.out.print("*");
}
System.out.println("");
}
输出:
*
***
*****
*******
*********
*******
*****
***
*
编辑 3: 星星对齐了,只需要去掉中间一排。
代码:
for (rows = 1; rows < height + 1 ; rows += 2){
for (spaces =0; spaces < height - 1 - rows / 2; spaces++){
System.out.print(" ");
}
for (stars = 0; stars < rows; stars++){
System.out.print("*");
}
System.out.println("");
}
for ( rows = height; rows > 0; rows -= 2){
for ( spaces =0; spaces < height - 1 - rows / 2; spaces++){
System.out.print(" ");
}
for ( stars = 0; stars < rows; stars++){
System.out.print("*");
}
System.out.println();
}
输出:
*
***
*****
*******
*********
*********
*******
*****
***
*
【问题讨论】:
-
发布预期的输出。
-
您的第二个内部循环应该使用
print而不是println。在第二个内循环结束后放置println。 -
我已经用固定代码更新了我的答案。它应该去掉中间的重复行。
标签: java loops for-loop infinite-loop