简体   繁体   中英

Boolean doesn't break for statement

I am new to the forum AND new to programming. I apologize in advance if my questions are really basic but I am really new to this and I had to learn a lot in a really short time, so I may miss a couple of concepts.

On to my question, I have a method who is supposed to check if a matrix still have spaces available and stop if it finds one.

The matrix has been initialized like this (I know it could be in one line, but the matrix is created within the constructor of an object)

protected char[][] matJeu = null;
matJeu = new char[10][10];

It has then been filled with spaces like this ' ' with a for statement and it works just fine

Here is the method

public boolean checkIfFull()
{
    boolean full = true;
    for (int i=0;i<matJeu.length || !full;i++)
    {
        for (int j=0;j<matJeu[i].length || !full ;j++)
        {
            if(matJeu[i][j]==' '){
                full = false;
            }
        }
    }
    return full;
} 

The problem is that when the full boolean turns to false, the for loops doesn't break and ends up by causing an ArrayOutOfBounds exception. If the matrix is full, it simply returns true. So I may be missing the correct way to cause a boolean to break a for loop.

Thank you in advance for your time.

The conditional part of the loop will cause the loop to continue as long as it returns true .

As soon as full=false is hit, then !full==true , and the conditional statement will always evaluate to true ( anything || true == true ), essentially putting you in an infinite loop with your current code.

To break your for loop, you need the conditional part to evaluate to false .

I'm not sure what you intend your loops to do, as stopping at the first space character doesn't seem like what you want based on the previous paragraph.

The problem is the or condition on your for loops.

for (int i=0;i<matJeu.length || !full;i++)

Here, the loop is going to continue executing so long as at least one of the conditions is true.

Because i<mathJeu.length is still true, the loop keeps executing, regardless of whether full is true or false .

Instead - what you want is an and condition.

for (int i=0;i<matJeu.length && full;i++)

This will tell it 'keep looping so long as it's below the array length AND we've detected it's still full'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM