0

I've created a random question generator. All questions are in the form: x=3/random number. The problem is that the program never recognizes the fact that the user's answer is correct. I've made it print out the answer and copy it into the answer input (text pane), yet it always prints out "wrong."

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

    //Generates random value for n (2 decimal plcae)   
    double nMin = 1.0;//minimum
    double nMax = 38.6;//maximum
    Random rn = new Random();  
    double nRand = nMin + (nMax - nMin) * rn.nextDouble();

    //Calculates corresponding value of v
    String x = String.format("%.2f", 3/nRand );
    double nAns = Double.parseDouble(x);//corresponding value of c
    check.setText(x);

    //displays question
    question.setText("n = " + String.format( "%.2f", nRand ) + "     v = ?");//question
    String answer = answerInput.getText();
    Double nUserA = Double.parseDouble(answer);
    //checks user's answer
    if(x.equals(answer)) {
        check.setText("correct");
    }    
    else
        check.setText("wrong");   

}                                      
Peter O.
  • 32,158
  • 14
  • 82
  • 96
Ben
  • 321
  • 1
  • 6
  • 21

1 Answers1

1

To compare if a String is equals to another in Java you have to use .equals() function, not ==. Like this:

s1.equals(s2);

Supposing that s1 and s2 are Strings so you have to change your condition to:

if(x.equals(answer))

I expect it helps to you!

Francisco Romero
  • 12,787
  • 22
  • 92
  • 167
  • Oh that's right, but the same problem remains. I originally compared doubles in the if-statement and forgot to change it. – Ben Jun 13 '15 at 21:39
  • @Benjamin I have a question. Why here: `question.setText("n = " + String.format( "%.2f", nRand ) + " v = ?");` did you put `nRand` instead of `3/nRand` like you said in the statement? – Francisco Romero Jun 13 '15 at 21:41
  • Because x, the correct answer is equal to 3/nRand – Ben Jun 13 '15 at 21:49
  • @Benjamin I'm sorry but I don't understand very well how you get the questions and answers. – Francisco Romero Jun 13 '15 at 21:51
  • 2
    @Benjamin You really can't compare `double`s using `==` either, because of the strong possibility of rounding errors. See http://stackoverflow.com/questions/1088216/whats-wrong-with-using-to-compare-floats-in-java. – ajb Jun 13 '15 at 22:01
  • 2
    @Benjamin If `x.equals(answer)` is returning `false` and you don't expect it to, could you get the program to print `x` and `answer` somewhere, and then look at them? Make sure you print it in a way so that leading and trailing spaces show up. That might help you see what the problem is, and if not, it would give you more information to provide us so that we can help you. – ajb Jun 13 '15 at 22:07