我被要求創建一個 java 程式來顯示一個倒置的數字金字塔(僅限 1 到 9)。用戶輸入多少行。
我不知道如何回圈并將數字限制為 9 并將其更改為右側。
我的代碼是:
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.print("Enter height:\t");
int height = sc.nextInt();
for (int row = height; row >= 1; row--) {
for (int col = 1; col <= row; col ) {
System.out.print("");
}
for (int k = 1; k <= row; k ) {
System.out.print(row "");
}
System.out.println();
}
}
}
輸出是:
Enter height: 12
121212121212121212121212
1111111111111111111111
10101010101010101010
999999999
88888888
7777777
666666
55555
4444
333
22
1
輸出應該是:
Enter height: 12
111111111111
22222222222
3333333333
444444444
55555555
6666666
777777
88888
9999
111
22
3
或者:
Enter height: 20
11111111111111111111
2222222222222222222
333333333333333333
44444444444444444
5555555555555555
666666666666666
77777777777777
8888888888888
999999999999
11111111111
2222222222
333333333
44444444
5555555
666666
77777
8888
999
11
2
uj5u.com熱心網友回復:
您的主回圈從高度運行到 0,這導致您列印的數字從高度到 1,輸出期望它按升序排列。
輸出進一步期望任何大于 9 的高度值再次被視為單位數增量,因此在 9 之后再次出現 1 而不是 10。
你有通過附加空格的寫想法,但要在java中附加空格,你實際上必須在兩個“”之間添加空格
例子:
System.out.print(" ").
修復上述所有問題的代碼片段應如下所示:
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.print("Enter height:\t");
int height = sc.nextInt();
for (int row = 1; row <=height; row ) {
for (int space = 1; space < row; space ) {
System.out.print(" ");
}
for (int val = row ; val <= height; val ) {
if(row>9){
System.out.print(row%10 1);
}
else{
System.out.print(row);
}
}
System.out.println();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/404994.html
標籤:
上一篇:為什么這種列印給定字串的每個字符的頻率的方法不起作用?
下一篇:PHP-根據索引加入陣列中的專案
