[英]Triple Nested For Loop with specific output (java)
我需要使用3“for”循環輸出來編寫一些java
122333444455555
22333444455555
333444455555
444455555
55555
我到目前為止的代碼:
public static void problemFour() {
for(int i = 5; i >= 1; i--) {
for(int a = 1; a <= i; a++) {
for(int b = 1; b <= a; b++) {
System.out.print(a);
}
}
System.out.println();
}
}
這輸出
111112222333445
11111222233344
111112222333
111112222
11111
我已經轉換了很多++的's,'s,>',5和1的組合。
我很困惑,如果有人能指出我正確的方向,那就太棒了。
你在線的開始方式和數字(此處字符)重復的次數上犯了錯誤。 修復它:
for(int i = 1; i <= 5; i++) { // Each iteration for one line
for(int a = i; a <= 5; a++) { // starts with a for ith line
for(int b = 1; b <= a; b++) { // a times `a` digit
System.out.print(a);
}
}
System.out.println();
}
要簡單地解決您的問題,首先要考慮打印此模式:
12345
2345
345
45
5
然后擴展它:在最里面的循環中,將重復的代碼等於數字時間,使用:
for(int b = 1; b <= a; b++) { // a times `a` digit
System.out.print(a);
}
我們可以使用數字1
僅打印一次, 2
次打印, 3
次打印三次等的觀察。
firstValueInLine
保持行開始的數字; number
是要打印的行號; counter
只是可確保number
被印刷number
倍
for (int firstValueInLine = 1; firstValueInLine <= 5; ++firstValueInLine) {
for (int number = firstValueInLine; number <= 5; ++number) {
for (int counter = 0; counter < number; ++counter) {
System.out.print(number);
}
}
System.out.println();
}
您可以嘗試以下方法。 它會工作。
public static void problemFour() {
for (int i = 1; i <= 5; i++) {
for (int a = i; a <= 5; a++) {
for (int b = 1; b <= a; b++) {
System.out.print(a);
}
}
System.out.println();
}
}
輸出:
122333444455555
22333444455555
333444455555
444455555
55555
這里是,使用第一個for-loop表示行數,第二個for-loop表示要打印的數字。 第3個for循環打印所需數量的顯示數字。 你所做的是相反的。 所以讓你的代碼反轉。
試試這個
public static void problemFour() {
for(int i = 1; i <= 5; i++) {
for(int a = i; a <= 5; a++) {
for(int b=0;b<a;b++){
System.out.print(a);
}
}
System.out.println();
}
}
查看內聯評論。
public static void main(String[] args) {
for (int i = 5, j = 1; i >= 1; i--, j++) { // Introduce a new variable j
for (int a = j; a <= 5; a++) { // change a=1 to a=j & a<=i to a<=5
for (int b = 1; b <= a; b++) {
System.out.print(a);
}
}
System.out.println();
}
}
輸出:
122333444455555
22333444455555
333444455555
444455555
55555
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.