2 回答

TA貢獻1842條經驗 獲得超13個贊
這里有兩個問題:
j >= 0
應該改為j > 0
您應該避免在以下情況下打印空白區域:
j == i
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a number 1...9 :");
int num = scan.nextInt();
scan.close();
for (int i = 1; i <= num; i++) {
for (int j = 2*(num-i); j > 0; j--)
if (num > 1)
System.out.print(" ");
for (int j = i; j >= 1; j--) {
if (j != i)
System.out.print(" ");
System.out.print(j);
}
System.out.println();
}
}
我收到以下輸出num = 5:
Please enter a number 1...9 :
5
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1

TA貢獻1853條經驗 獲得超9個贊
嘗試添加一個第一次跳過空格的 if 語句,例如:
for(int j = i; j >= 1; --j)
{
if(j == i)
System.out.print(j);
else
System.out.print(" " + j);
}
添加回答
舉報