0

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
banking 5
month 1
month 2
month 3

1
  • Check the scope of your variables. Commented Jun 21, 2011 at 5:14

5 Answers 5

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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++;


    }

}

3 Comments

thanks! that is, yeah, I need reset the counter of the 2nd loop (Im new to programming)
I see no point in this spoon feeding here. @Vineet Reynolds had given the correct hint which the op should've followed up on. That way he'd have understood his error better.
I do actually agree. The only reason I posted code is because I overlooked the homework tag. @Vineet Reynolds did post correct information that would have lead the op to the correct answer.
0

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.

Comments

0

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

Comments

0

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");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.