Home > database >  My for loop keeps going despite the condition met
My for loop keeps going despite the condition met

Time:12-10

n is equal to 2 when its loop is over, but by the last "if" statement it's somehow 3. ) can not figure out where it's changing. because the last if condition isn't being met the for loop keeps going instead of returning true (for(int i=0;i<Board[i].length;i )) and ) get an out of bounds exception.

so two questions -

  1. can u spot where n changes?
  2. how come the for loop with I keeps going despite the condition being met? Board[i].length=3 and the loop just keeps going and gives me an out of bounds exception instead of exiting the for loop and returning me the false after it.
public boolean ColChecker() {
    int n=0;
    // create boolean array and set all values to false
    boolean[] isExist = new boolean[10];
    for(int i=0;i<isExist.length;i  ) 
        isExist[i]=false;
        
    //loop over columns and test using whosThereCol method
    for(int i=0;i<Board[i].length;i  ) {
        for(int col=0;col<Board[0][0].getLength();col  ) {
            for(n=0;n<Board.length;n  ) 
                Board[n][i].whosThereCol(col,isExist);
                    
            //if array still has missing values, column incomplete - return false
            for(int j=1;j<10;j  ) 
                if(!isExist[j]) 
                    return false;
            //if no missing values, initialize array to false values for next iteration of for loop
            for(int j=1;j<10;j  ) 
                isExist[j]=false;
                            
                    
        // "if" statement checks if this is the last column in the last square, if so, we passed all the tests. return true     
        if(i 1==Board[0].length&&col 1==Board[0][0].getLength()&&n 1==Board.length)
            return true;                
        }
    }
    return false;
}

CodePudding user response:

It's because the n at the end of the for statement will get executed after the last loop also.

Consider this code:

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

this will output:

0
1
2
3
4
5
6
7
8
9
=========
10

CodePudding user response:

Normally you don't need the condition at the end. Since you can also simply say when all 3 loops have run through: return true; What I first notice as an error, you compare the top of your For loop with Board[i], but further down the comparison value is Board[0]. So your condition can't be true if not the length of Board[i] is always the same. enter image description here

You also should change your For Loop Order maybe to this:

 for(n=0; n<Board.length; n  ){
            for(int i=0;i<Board[n].length;i  ) {
                for(int col=0;col<Board[n][i].getLength();col  ) {
                    Board[n][i].whosThereCol(col,isExist);
                }
                //Your further Code
            }
        }
  • Related