JAVA - 虽然它不应该循环退出?

时间:2014-03-08 23:02:44

标签: java while-loop conditional-statements

我一直试图为自己解决这个问题大约2个小时。我猜有人会立即发现我的问题。所以我的问题是while循环(或.equals给出了错误的结果)。这是代码:

        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

因此,当变量“type(string)”不等于“questionArray.get(i).questionType(string)”时,它的问题就出现了它不应该出现的问题。那么让我们说“type ='hello'”和“questionArray.get(i).questionType ='hi'”它是否会出现在循环中?

上面代码中代码的输出是:

  
    

1 type = general - questionType = sport

  

那么这里有什么问题?为什么说第一个条件是真的呢?第二个条件是假(这是正确的)继承人方法的代码“hasQuestionBeenAsked”:

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;
}

谢谢!如果您需要任何额外信息,请告诉我!

1 个答案:

答案 0 :(得分:2)

这很简单 - 这是因为你通过使用否定运算符来否定错误 - (!)。所以,即使你有假,你最终也会得到真,因为(不是)假=真。在您的情况下,请使用

// Remove the negation - !
while(type.equals(questionArray.get(i).questionType) && Questions.hasQuestionBeenUsed(i)) {
        i++;
}
相关问题