开发者

java, processing Nested Loop?

开发者 https://www.devze.com 2023-03-14 12:15 出处:网络
I use this code: int contadorA = 1, contadorB = 1; while (contadorA <= 5) { println (\"banking \" + contadorA);

I use this code:

int contadorA = 1, contadorB = 1;

while (contadorA <= 5) {
    println ("banking " + contadorA);
    contadorA++;

    while (contadorB <= 3) {
         println ("month " + contadorB);
        contadorB++;
    }
}

the code print this:

banking 1

month 1

month 2

month 3

banking 2

banking 3

banking 4

banking 5

AND I NEED THAT PRINT THIS:

banking 1

month 1

month 2

month 3

banking 2

month 1

month 2

month 3

banking 3

month 1

month 2

month 3

banking 4

month 1

month 2

month 3

ba开发者_StackOverflow中文版nking 5

month 1

month 2

month 3


I won't post code, my apologies.

I'll give a hint. In the inner loop, you are not resetting the counter, on entering it. This means that contadorB's value after the execution of the first outer loop is 4, and it will never enter the inner loop again.

Here's another hint. Step through the code in the debugger (and watch the value of contadorB) if you haven't understood my earlier hint.


You aren't resetting the second counter inside the loop. You need to do this:

int contadorA = 1, contadorB = 1;

while (contadorA <= 5) {

    println ("banking " + contadorA);
    contadorA++;

    contadorB = 1;
    while (contadorB <= 3) {

    println ("month " + contadorB);
    contadorB++;


    }

}


Declare the int contadorB = 1; in the first while loop but before second while loop. In other words, you are just resetting the variable for every iteration of the first while loop.


Check the value of contadorB at the end of the second while loop.


This code will point out your issue:

int contadorA = 1, contadorB = 1;

while (contadorA <= 5) {
    println ("banking " + contadorA);
    contadorA++;

    while (contadorB <= 3) {
         println ("month " + contadorB);
        contadorB++;
    }
    println ("contadorA: " + contadorA + "\n contadorB: " + contadorB + "\n");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消