簡體   English   中英

我想弄清楚我的代碼有什么問題

[英]i want to figure out what's wrong in my code

我想使用 while 循環制作這樣的 java 模式

*  *  *  * 
*  *  * 
*  * 
*

這是我的代碼

int i = 4;
int j = 0;

while (i >= 0) {
    while (j < i) {
        System.out.print(" * ");
        j++;
    }
    
    System.out.print("\n");
    i--;
}

但它給 output 是這樣的:

*  *  *  * 

有誰知道該怎么辦......?

嘗試考慮這個可能會幫助你!

使用 FOR 循環

public class DownwardTrianglePattern {  
    public static void main(String[] args) {  
        int rows = 4;      
        //outer loop  
        for (int i = rows-1; i >= 0 ; i--) {  
            //inner loop  
            for (int j = 0; j <= i; j++) {  
                //prints star and space  
                System.out.print("*" + " ");  
            }  
            //throws the cursor in the next line after printing each line  
            System.out.println();  
       }  
    }  
}  

使用 While 循環

public class Itriangle {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter N : ");
        int n = sc.nextInt(); 
        System.out.print("Enter Symbol : ");
        char c = sc.next().charAt(0);
        int i = n, j;
        while(i > 0) {
            j = 0;
            while(j++ < i) {
                System.out.print(c);
            }
            System.out.println();
            i--;
        } 
    }
}

在我--之后你可以 j=0;

您的代碼中的問題是,在完成兩個 while 循環后的第一次迭代中,變量的值是 i=3 和 j=4。 因此,對於下一次迭代,第一個 while 循環將在條件為真時運行,即 3>=0 但對於下一個 while 循環,條件將為假,因為 j ie 3 不小於 i ie 3。這就是下一個循環執行的原因不執行,你得到的是 output。

當你完成內部循環時,你必須重置 j 值,否則它的值將保持為 4,不小於i值。 您可以在開始內部 while 之前重置該值

int i = 4;
int j = 0;

while (i >= 0) {
    j = 0;
    while (j < i) {
        System.out.print(" * ");
        j++;
    }
    
    System.out.println(""); // println will work same as System.out.print("\n") in this scenario
    i--;
}

j 需要在循環內初始化。

我更改了代碼如下。 它給出了正確的 output

   int i = 4;
        while (i >= 0) {
            int j = 0;
            while (j < i) {
                System.out.print(" * ");
                j++;
            }

            System.out.print("\n");
            i--;
        }

請在 j 循環后重置 j

    int i = 4;
    int j = 0;

    while (i >= 0) {
        while (j < i) {
            System.out.print(" * ");
            j++;
        }
        j = 0;

        System.out.print("\n");
        i--;
    }

順便說一下,你的問題可以用遞歸很好地解決

public static void main(String[] args) {
    printLine(4);
}

private static void printLine(int numberOfStars) {
    if(numberOfStars == 0) {
        return;
    }

    System.out.println("* ".repeat(numberOfStars));

    printLine(numberOfStars - 1);
}

Output

*  *  *  *  
*  *  *  
*  *  
*  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM