在使用ifs的嵌套for循环中我的逻辑错误在哪里?

时间:2015-06-12 09:59:02

标签: java playframework ebean

我编写了一些测验。首先,用户可以提出问题并回答问题。这些都保存在问题/答案表中。

如果此表中有足够的条目,则可以启动测验。测验通过问题/答案表中的条目,随机选择一个问题并询问用户问题。他的答案保存在测验表中。

测验表中的条目将当前用户考虑在内,因此如果已经有用户的条目(可能他之前已经被问过),则答案会更新测验表中的条目。如果之前询问过用户问题,则会在测验表中创建一个新条目。

大部分内容都或多或少,但不知何故,测验表中的条目不会更新,我也不明白为什么。那么我的逻辑错误在哪里呢?

//Creates a list.The user answers the question via radiobuttons. 
//All quiz-entries that match the question_ID get put into the list. 
//Bob and Tim could have answere the same question, 
//so the question_ID could be in there several times
List<Quiz> tempQuizList = Quiz.find.where().like("question_ID", clickedRadioAnswer.questionID).findList();

User currentUser = request().name();

if( tempQuizList.size() > 0 ){
    // Go through all entries in the quiz-table
    for (Quiz quizItem : Quiz.find.all()) {
        // If the user from the quiz-table entry is the same as the current user
        if((quizItem.userID).equals(currentUser.email)){
            if(clickedRadioAnswer.answerID.equals(bestAnswer.answerID)){
                // If user has answered correctly, update the entry with the user and an interval to postpone the time when the user has to answer the question again
                Quiz.updateAnswer(clickedRadioAnswer.questionID, currentUser.email, 5000);
            } 
            else{
                Quiz.updateAnswer(clickedRadioAnswer.questionID, currentUser.email, 0);
            }
        }
        if(!(quizItem.userID).equals(currentUser.email)){
            if(clickedRadioAnswer.answerID.equals(bestAnswer.answerID)){
                Quiz.createAnswer(clickedRadioAnswer, currentUser, 5000);
            } 
            else{
                Quiz.createAnswer(clickedRadioAnswer, currentUser, 0);
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我找到了一个非常糟糕的解决方案:

在我的for循环中,我问,如果数据库中问题的用户与当前登录的用户相同。如果我将另一个.like()添加到我的列表中,我的结构将变为方式更简单的:

List<Quiz> tempQuizList = Quiz.find.where()
.like("question_ID", clickedRadioAnswer.questionID).findList();

变为:

List<Quiz> tempQuizList = Quiz.find.where()
.like("question_ID", clickedRadioAnswer.questionID)
.like("user_id", currentUser.email).findList();

有了这个,我的大if块的第二部分就不再需要了,因为100%当前用户的用户(否则问题不会被放入列表中):

if( tempQuizList.size() > 0 ){              
    if(clickedRadioAnswer.answerID.equals(bestAnswer.answerID)){
        Quiz.updateAnswer(clickedRadioAnswer.questionID, currentUser.email, 5000);
    } 
    if(!clickedRadioAnswer.answerID.equals(bestAnswer.answerID)){
        Quiz.updateAnswer(clickedRadioAnswer.questionID, currentUser.email, 0);
    }
}

// Quiz is empty or user has no quizquestion open
if(tempQuizList.size() == 0){
    if(clickedRadioAnswer.answerID.equals(bestAnswer.answerID)){
    Quiz.createAnswer(clickedRadioAnswer, currentUser.email, 5000);
} 
else{
    Quiz.createAnswer(clickedRadioAnswer, currentUser.email, 0);
}

我尝试使用调试器,但发现它实际上很难看到,错误在哪里。相反,我和朋友聊了一下并向他解释,我在做什么。然后他指出,for-loop太多了。我们一起找到了双重解决方案。它看起来不漂亮,但完成了工作。