我是论坛的新手,也是编程新手。 如果我的问题非常基本,我会提前道歉,但我对此非常陌生,而且我必须在很短的时间内学到很多东西,所以我可能会错过几个概念。
关于我的问题, 我有一个方法,它应该检查矩阵是否仍有空格,如果找到则停止。
矩阵已经像这样初始化了(我知道它可以在一行中,但矩阵是在对象的构造函数中创建的)
protected char[][] matJeu = null;
matJeu = new char[10][10];
然后充满了像这样的空间' '使用for语句,它可以正常工作
这是方法
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;
}
问题在于当完整布尔值变为false时,for循环不会因为导致ArrayOutOfBounds异常而中断并结束。如果矩阵已满,则只返回true。所以我可能错过了使布尔值打破for循环的正确方法。
提前感谢您的时间。
答案 0 :(得分:4)
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.
答案 1 :(得分:1)
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'.