
我們的任務是創建一個數字金字塔,隨著它的下降而降低其值,但是每次迭代都會以奇數重復它。我試圖瞄準的輸出是:
5
444
33333
2222222
111111111
但它不會列印完整的金字塔,只會列印從 5 到 3 的那些數字。
這是我使用的代碼:
import java.util.Scanner;
public class LoopExercise2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int rows = 5;
// row counter; total rows will be decided by the scanned input
for (int counter = 1; counter <= rows ; counter) {
//System.out.print("7");
// space counter before the number; creates the pyramid effect
for (int space = 0; space <= rows ; space ) {
System.out.print(" ");
}
// per iteration, prints an odd number of values
int n_counter = 0; // Initialize value to 0
while (n_counter != 2 * counter - 1) {
System.out.print(rows);
n_counter;
}
// deducts 1 from the scanned input
rows--;
// prints a space to break the line
System.out.println();
}
}
}
uj5u.com熱心網友回復:
您的回圈停止條件每次都在變化。counter <= rows正如你所擁有 counter和rows--
因此,回圈停止在 initial rows value / 2
我建議您為列印和遞減的數字使用單獨的變數
uj5u.com熱心網友回復:
嘗試這個。
public static void main(String[] args) {
int rows = 5;
for (int i = rows, j = 1; i > 0; --i, j = 2)
System.out.println(" ".repeat(i) Integer.toString(i).repeat(j));
}
輸出:
5
444
33333
2222222
111111111
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/336431.html
