-2

this may be a simple problem, but I've looked for an answer and I'm just not finding it anywhere. I'm trying to use a method to check if an inputted answer is correct compared to the actual answer. The actual answer is defined by a setter, and the getter works also. But in the method where it's compared it becomes null. This isn't a question about why comparing them returns null, but why correctAnswer is null in the first place. I'm confused because getCorrectAnswer() works as intended.

Here is the code:

public class MultipleChoiceQuestion implements Question {

String question;
String correctAnswer;

public String getQuestion() 
{
    return question;
}

public boolean isCorrectAnswer(String answer) 
{
    if (answer != correctAnswer)
    {
        return false;
    }
    return true;
}

public String getCorrectAnswer() 
{
    return correctAnswer;
}

public void setQuestion(String questionText){
    question = questionText;
}

public void setAnswer(String answer){
    correctAnswer = answer;
}

}

"answer != correctAnswer" doesn't work because correctAnswer is null in that method.

dkrusch
  • 1
  • 1

1 Answers1

0

You shouldn’t use equality for classes unless you want to check that two are perfectly identical, that is, the same object. You should use Object.equals. So answer.equals(correctAnswer) is more correct. Also, are you sure that the setter was called first?

Josh Ghiloni
  • 1,260
  • 8
  • 19
  • I tried .equals and changing the order but that didn't seem to do anything. Calling getcorrectanswer works fine – dkrusch Dec 03 '17 at 23:49