如何使用嵌套 for 循环制作菱形 [英] How to make a diamond using nested for loops
问题描述
所以我被指派用 Java 制作带有星号的钻石,我真的很困惑.到目前为止,这是我想出的:
So I was assigned to make a diamond with asterisks in Java and I'm really stumped. Here's what I've come up with so far:
public class Lab1 {
public static void main(String[] args) {
for (int i = 5; i > -5; i--) {
for (int j = 0; j < i; j++) {
System.out.print(" ");
}
for (int j = 0; j >= i; j--) {
System.out.print(" ");
}
System.out.println("*");
}
}
}
推荐答案
为了制作钻石,您需要设置空间和星星的形状.因为我是初学者,所以我只使用嵌套循环制作了这个简单的程序.
In order to make a diamond you need to set spaces and stars in shape. I have made this simple program using only nested loops since I am a beginner.
public class Diamond {
public static void main(String[] args) {
int size = 9,odd = 1, nos = size/2; // nos =number of spaces
for (int i = 1; i <= size; i++) { // for number of rows i.e n rows
for (int k = nos; k >= 1; k--) { // for number of spaces i.e
// 3,2,1,0,1,2,3 and so on
System.out.print(" ");
}
for (int j = 1; j <= odd; j++) { // for number of columns i.e
// 1,3,5,7,5,3,1
System.out.print("*");
}
System.out.println();
if (i < size/2+1) {
odd += 2; // columns increasing till center row
nos -= 1; // spaces decreasing till center row
} else {
odd -= 2; // columns decreasing
nos += 1; // spaces increasing
}
}
}
}
如您所见,nos
是空格数.需要减少到中排,需要增加星数,但到中排后则相反,即空格增加,星星减少.
As you can see nos
is the number of spaces. It needs to be decreased until the center row, and the number of stars needs to be increased but after the center row it's the opposite, i.e spaces increase and stars decrease.
size
可以是任意数字.我在这里将它设置为 9,所以我将有一个大小为 9 的星,最大为 9 行和 9 列......空间数 (nos
) 将是 9/2 = 4.5代码>.但是java会把它当作4,因为
int
不能存储十进制数,中间行会是9/2 + 1 = 5.5
,这将导致5为int
.
size
can be any number. I set it to 9 over here so I will have a size 9 star that is 9 rows and 9 columns max... number of space (nos
) will be 9/2 = 4.5
.
But java will take it as 4 because int
can not store decimal numbers and the center row will be 9/2 + 1 = 5.5
, which will result in 5 as int
.
所以首先你要做行......因此有 9 行
So first you will make rows... 9 rows hence
(int i=1;i<=size;i++)//size=9
然后像我一样打印空格
(int k =nos; k>=1; k--)//nos 为 size/2
最后是星星
(int j=1; j<=odd;j++)
一旦行结束...
您可以使用 if 条件调整星号和空格.
You can adjust stars and spaces using an if condition.
这篇关于如何使用嵌套 for 循环制作菱形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!