Question

So I have a loop that is wrapped around a loop and an if statement. When running the program however, it gets out of the inner loop (as planned) and then it fails the if statement (also as planned), resorting to the else statement which is a simple print.

What I /wanted/ to happen was have it then (in the case the if fails), restart to the original inner loop--hence the outer loop. But instead, after it fails the if statement, it begins to loop "phrase2" over and over.

Here is the simplified code:

int x = 1;
int y = 1;
int i = 0;
while(i == 0)
{
    while(<condition that is false>)
    {
        System.out.println("phrase1");
        a = input.nextInt();
        b = input.nextInt();        
    }
    if(<condition that is false>)
    {
        i = 1;
    }
    else
    {
        System.out.println("phrase2");
    }
}

Thanks for your help regardless!

EDIT: For the sake of emphasis... What happens: Infinite loop spewing "phrase2". What I wanted: After the else is executed, I wanted to be brought into the inner loop again.

Was it helpful?

Solution

Whatever condition you're using in the inner loop, just make sure it's true.

else
{
    System.out.println("phrase2");
    // SET THIS TO TRUE: <condition that is false>
}

This way, the inner loop will trigger again.

OTHER TIPS

Your control never enters the below if statement

if(<condition that is false>)
{
    i = 1;
}

You might need to adjust your conditions so that it comes into the above if block. Introduce a System.out.println inside if statement to debug

It looks like you have some code that you probably want to run once, unless something went wrong, and then you want to go back and retry. The idiom I usually use for that looks like

boolean needToRetry;
do {
    needToRetry = false;
    // do whatever
    if (somethingWentWrong) {
        needToRetry = true;
        // set this at any point where you find you will need to go back
    }
} while (needToRetry);

The important thing is that you need to reset your flag (needToRetry) at the beginning of the loop, each time. (P.S. There are other ways to do this using break or continue, although I personally don't like using continue.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top