我正在尝试创建一个程序,该程序将按该顺序显示以下结果。
N=1 * N=2 ** * N=3 *** ** *
这是我的代码:
public static void main(String[] args) {
int Output;
int asterisks;
Scanner input= new Scanner(System.in);
System.out.println("Enter number of output you want: ");
Output= input.nextInt();
for(int j=1; j<=Output;j++){
System.out.println("N= "+ j);
for (int i=j; i>=1; i--){
asterisks=i;
for(int k=1; k<= asterisks; k++){
if(k==asterisks){
System.out.println("*");
}
else
System.out.print("*");
}
}
}
}
}
But so far the code I wrote is outputing
N= 1
*
N= 2
**
*
N= 3
***
**
*
N= 4
****
***
**
*
所以我想我需要反转这个 for(int k=1; k<= asterisks; k++)
.
最佳答案
试试这个。
for (int i = 1; i <= Output; ++i) {
System.out.println("N= " + i);
for (int j = 0; j < i; ++j) {
for (int k = 0; k < i; ++k) {
System.out.print(k < j ? " " : "*");
}
System.out.println();
}
}
关于Java for 循环星号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40063733/