這是問題。我必須列印這種模式,例如對于 n = 5
For n = 5
****1
***232
**34543
*4567654
567898765
我已經為這個問題撰寫了邏輯,但我無法解決它。我無法列印最后一個圖案,即減少一個 2 4,3 5,4
Here's my pattern For n = 5
****1
***232
**34544
*4567666
567898888
誰能幫助我,告訴我我的邏輯有什么問題。如何修復它
我的代碼在下面
import java.util.Scanner;
import java.lang.*;
public class Main {
public static void main(String[] args) {
solve();
}
public static void solve(){
int n;
Scanner obj = new Scanner(System.in);
n = obj.nextInt();
for(int row =1;row<=n;row ){
int ans1 = row;
int spaces =1;
for( spaces = 1;spaces<=n-row;spaces ){
System.out.print("*");
}
for (int pattern01 = 1; pattern01<=row;pattern01 ){
System.out.print(ans1);
ans1 = ans1 1;
}
for ( int pattern2 = 1 ; pattern2<=row-1; pattern2 ){
ans1= 2*row-2;
System.out.print(ans1);
ans1--;
}
System.out.println();
}
}
}
uj5u.com熱心網友回復:
您遇到的問題是您沒有正確減少“ans1”。如果您不確定如何使用除錯器,請通過控制臺使用列印輸出陳述句觀察您的輸出。特別是當“ans1”應該倒數時的第三個回圈。另外,請記住退出第二個 for 回圈后 'ans1' 的值。
當您開始從行號變數開始計數時,這是您的第二個回圈。每次迭代將“ans1”遞增 1。
for (int pattern01 = 1; pattern01 <= row;pattern01 ) {
System.out.print(ans1);
ans1 = ans1 1;
}
要考慮的一件事是,您正在遞增“ans1”,在您進入第三個回圈遞減之前它的值是多少?在進入回圈并開始列印之前,您需要在這里做一些事情。
此外,在您的第三個回圈中,您沒有正確遞減。您應該倒數,或者更確切地說只是減 1。
for(int pattern2 = 1;pattern2 <= row-1; pattern2 ){
ans1= 2*row-2; // Your focus should be here, does this look right? Do you need it?
System.out.print(ans1); // You should decrement first and then print
ans1--; // this is correct, but in the wrong spot
}
我知道你可以成功 :) 你明白了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/512355.html
