Search code examples
javajoptionpane

JOptionPane - Correct/incorrect answers


So i am new to programming and I have been trying to make a simple program for practice.

It asks you questions and you answer it.

I can't seem to get it to work right. It either Says its correct when it's not or that it isn't correct when it is.

Here is my code

// Questions

    String q1;
    JOptionPane.showInputDialog(null, "1). What is the name of our sun?");

    if(q1 == "Sol") {
        JOptionPane.showMessageDialog(null, "Correct!");
    }
    else {
        JOptionPane.showInputDialog(null, "Sorry that is incorrect :(");
        }

What am I missing?


Solution

  • First of all assign a value to q1 otherwise you will compare the null value.

    Secondly you can't use the equality operator == for string comparison. You need to use the equals method of String. Thus q1.equals("Sol") instead.

    This is a basic programming mistake for beginners. If you use == with strings it will compare the object references of the strings, not the actual values that they store. Imagine a string s1 that is located in memory location 1000 with value "Answer" and string s2 located in memory location 1001 with value "Answer" then

    s1 == s2 would compute into 1000 == 1001
    

    which is of course false. What you want to do is compare

    "Answer" == "Answer". For that you need to use s1.equals(s2)
    

    This counts for every non-primitive type! Every object has the method equals which you can use to compare the values of the object. For the primitive types byte, char, short, int, long you can keep on using == to compare values.