簡體   English   中英

Java中的Loop inside Loop(簡單)

[英]Loop inside Loop in Java (simple)

我正在做一個練習,我必須打印從 0 到 10 遞增的數字行“x”(是輸入)。如果我輸入 3,則 output 應該如下所示

012
345
678

012
345
678

012
345
678

但相反,我得到 3 行的 0 到 10 計數。
我知道它可能很容易編碼,但我被困在其中!
我想我並沒有很好地理解嵌套循環:(

public class quadrats {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        int q = in.nextInt();

        for (int j = 0; j < q; j++) {
            for (int i = 0; i <= 10; i++) {
                System.out.print(i);
            } 
            System.out.println();
        } 
    }

}

為此,您不需要兩個循環。 您只需要在每 3 個字母后打印一個換行符,並在每 3 行后打印一個額外的換行符。 您的代碼可以是:

public class quadrats {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        int q = in.nextInt();
        int lines = 0;
        int letters = 0;
        while (lines < q) {
            System.out.print(i);

            if (letters && letters % q == 0) {
                System.out.println();
                lines++;
            }
            if (lines && lines % q == 0) {
                System.out.println();
                letters = 0;
                continue;
            }
            letters++;
        }
}

PS:我自己沒有嘗試過這段代碼。 但概念是一樣的。

您可以嘗試使用以下代碼

public class quadrats {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        int q = in.nextInt();

        for (int j = 0; j < q; j++) {
            for (int i = 0; i < 9; i++) {
                if(i%3 == 0)
                   System.out.println();
                System.out.print(i);
            } 
            System.out.println();
        } 
    }
}

上面的答案應該可以解決您的問題,因此我將嘗試解釋您的代碼的作用。

讓我們從第一個 for 循環中的代碼開始:

for (int i = 0; i <= 10; i++) {
   System.out.print(i);
} 
System.out.println();

首先,我們有一個循環遍歷從 0 到 10 的數字,output 是:

012345678910

以及之后的新行。

這意味着您的程序的 output 將打印上述 output q次。

012345678910

012345678910

012345678910

分別打印 X 行和 X 列的 X 個象限

Scanner in = new Scanner(System.in);
int q = in.nextInt();

// q quadrants
for (int iQuadrat = 0; iQuadrat < q; iQuadrat++) {

    // count will keep track of the last number you print
    int count = 0;
    // q rows
    for (int iRow = 0; iRow < q; iRow++) {
        // q cols
        for (int iCol = 0; iCol < q; iCol++) {
            System.out.print(count);
            // increment the count and take its modulo 10 so it stays between 0 and 9
            count = (count+1)%10;
        }
        // line return at the end of the row
        System.out.println();
    }
    // line return between quadrants
    System.out.println();
}

對於 12 的輸入,它將打印該象限的 12 次

012345678901
234567890123
456789012345
678901234567
890123456789
012345678901
234567890123
456789012345
678901234567
890123456789
012345678901
234567890123

暫無
暫無

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

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