JAVA-While循环在不应该退出时退出?
我已经试着为自己解决这个问题大约两个小时了。我猜有人会马上发现我的问题。所以我的问题是一个while loopor.equals给出了一个错误的结果。代码如下:JAVA-While循环在不应该退出时退出?,java,while-loop,conditional-statements,Java,While Loop,Conditional Statements,我已经试着为自己解决这个问题大约两个小时了。我猜有人会马上发现我的问题。所以我的问题是一个while loopor.equals给出了一个错误的结果。代码如下: Integer i = 0; while(!type.equals(questionArray.get(i).questionType) && Questions.hasQuestionBeenUsed(i)) { i++; } Sy
Integer i = 0;
while(!type.equals(questionArray.get(i).questionType) && Questions.hasQuestionBeenUsed(i)) {
i++;
}
System.out.println(i + " type=" + type + " - questionType" + questionArray.get(i).questionType);
usedQuestionIndexes.add(i); //if question index has not been used - add it to used indexes
所以这里的问题是,当变量类型字符串不等于questionArray.geti.questionType字符串时,它将退出,而它不应该是。那么让我们假设type='hello'和questionArray.geti.questionType='hi'它是从循环中出来的吗
上述代码的代码输出如下:
1类型=一般-问题类型=运动
那么这里的问题是什么?为什么说第一个条件是正确的,而事实并非如此?第二个条件是说False,这是正确的,方法的代码已被拒绝:
public static Boolean hasQuestionBeenUsed(Integer questionIndex) {
for(Integer usedQuestionIndex : usedQuestionIndexes) {
if(questionIndex.equals(usedQuestionIndex)){
return true; //if index is found in usedQuestionIndexes array it will return that the index has been used
}
}
return false;
}
谢谢!如果你需要任何额外的信息,告诉我 这很简单-因为您使用否定运算符来否定false-!。所以,即使你有假,你也会以真结束,因为不假=真。在您的情况下,使用
// Remove the negation - !
while(type.equals(questionArray.get(i).questionType) && Questions.hasQuestionBeenUsed(i)) {
i++;
}
为什么在应该使用Boolean和int时使用Boolean和Integer?因为您使用的是一个!=>!type.equalsquestionArray.geti.questionType.@JustinJasmann但它需要循环,直到type等于questionType?但您刚才说过,如果您有hello和hi,那么!你好,equalshi已经出来了。扩大了,就是这样!假即真。如果此时条件的另一半为假,您将退出。@JustinJasmann抱歉,是的,您是正确的,愚蠢的我。谢谢但我想让它继续循环,如果类型不等于questionType?在长时间内,虽然类型不等于questionArray.geti.questionType和question未被使用,但保持循环