[英]Java for loop spacing the result
我正在Java類中編寫程序,因此我需要打印一個星形金字塔。 我的代碼顯示為:
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number between 1 and 20: ");
int value = sc.nextInt();
System.out.println("Pattern B: ");
for(int x = 1; x <= value; x++){
for(int y = value; y>=x; y-- ){
System.out.print("*");
}
System.out.print("\n");
}
我的結果顯示一行5星,然后輸出4、3、2、1(如果用戶輸入數字5)。 我想要的是將星星全部推向右側。 如:
5星的直線,(星空)直線的4星,(兩個星空)直線的3星,(三個星空的)直線2星,(四個星空的)直線1星
我說得通嗎
我是否應該引入if then語句,檢查變量y並相應地增加空格? 對不起,讓我感到困惑。
您可以執行以下兩項操作之一:
x
for
循環中引入另一個for
循環,該循環將循環x
次,以print
x
空格字符,或者 y
for
循環修改for
從1
到value
,然后在其中添加if
語句以決定打印空格還是*
。 您可以引入一個新的for
循環,以在打印星星之前打印所需數量的空格:
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number between 1 and 20: ");
int value = sc.nextInt();
System.out.println("Pattern B: ");
for(int x = 1; x <= value; x++){
for(int c = value-x; c<value; c++){
System.out.print(" ");
}
for(int y = value; y>=x; y-- ){
System.out.print("*");
}
System.out.print("\n");
}
請記住,如果您想要一個真正的金字塔,則必須跳過每兩個數字。 例如,如果您選擇5,並決定為每個數字打印一行直到0,這是您最好的選擇:
*****
****
***
**
*
如果您跳過,則可以得到如下內容:
*****
***
*
現在,您所需要做的就是看看距底座有多遠才能獲得空格數,將其除以2,就可以得到上一個和下一個空格。
您可以嘗試如下操作:
int spacing;
for(int x = 0; x < value; x=x+2){
for(int y = value; y>x; y-- ){
spacing = x/2;
for(int i = 0; i < spacing; ++i)
System.out.print(" ");
System.out.print("*");
for(int i = 0; i < spacing; ++i)
System.out.print(" ");
}
System.out.print("\n");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.