Ati*_*hah 8 java for-loop nested-loops
我正在尝试使用for循环和嵌套for循环制作圣诞树.对我来说,我需要能够用*制作金字塔.我已经尝试了无数次,但我遇到了问题.这是我的代码:
for(int i=1;i<=10;i++){
for(int j=10;j>i;j--){
System.out.println(" ");
}
for(int k=1;k<=i;k++){
System.out.print("*");
}
for(int l=10;l<=1;l++){
for(int h=1;h<=10;h++){
System.out.print(" ");
}
}
System.out.println();
}
Run Code Online (Sandbox Code Playgroud)
我想要做的是:
*
***
*****
*******
Run Code Online (Sandbox Code Playgroud)
Sou*_*nta 11
试试这个更简单的代码:
public class ChristmasTree {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10 - i; j++)
System.out.print(" ");
for (int k = 0; k < (2 * i + 1); k++)
System.out.print("*");
System.out.println();
}
}
}
Run Code Online (Sandbox Code Playgroud)
它使用3个循环:
Bur*_*man 10
你可以用简单的逻辑来做到这一点
for (int i = 0; i < 4; i++)
System.out.println(" *******".substring(i, 4 + 2*i));
Run Code Online (Sandbox Code Playgroud)