Home > OS >  How can I translate this if/else statement into a while loop?
How can I translate this if/else statement into a while loop?

Time:03-20

I am trying to convert this if/else statement into a while loop but have no idea what to do. Could someone help me with problem?

int no = 0;
    if        ((piece(0) == no) && (piece(1) == no) && (piece(2) == no) && (piece(3) == no)
            || (piece(1) == no) && (piece(2) == no) && (piece(3) == no) && (piece(4) == no)
            || (piece(2) == no) && (piece(3) == no) && (piece(4) == no) && (piece(5) == no)
            || (piece(3) == no) && (piece(4) == no) && (piece(5) == no) && (piece(6) == no)
            || (piece(4) == no) && (piece(5) == no) && (piece(6) == no) && (piece(7) == no)) {
        System.out.println("True");
    }
    else
        System.out.println("False");

CodePudding user response:

You need to add a submethod

public boolean checkFourInARow(int seed) {
  return piece(seed) && piece(seed   1) && piece(seed   2) && piece(seed   3)
}

Then replace the code you have posted with

while (int i < 5) {
  checkForInARow(i);
}

CodePudding user response:

Not a while loop, but two for loops could reduce some of your redundancy:

void foo()
{
    outer:
    for (int i = 0; i < 4;   i)
    {
        for (int j = i; j < i   4;   j)
        {
            if (piece(j) != 0) continue outer;
        }
        System.out.println("True");
        return;
    }
    System.out.println("False");
}
  • Related