Search code examples
javaloopsjtextfield

How to make sure that values written in a textfield are the same using a simple loop function?


I wrote a simple code just to check the values between textfields and compared whether they are the same or not. I want them to be the same, if not it will produce an error. It's about rewriting an email.

    String a = studentemail.getText();
    String b = rewritestudentemail.getText();

    if(a != b){
         JOptionPane.showMessageDialog( null, "Student Email rewritten incorrectly.","Error!",JOptionPane.OK_OPTION);

    }

The program persists that there is an error even though I indicated the same string values in both of the fields. Why's that?


Solution

  • Change your conditional to be this:

    if(!a.equals(b))
    {
       JOptionPane.showMessageDialog( null, "Student Email rewritten
       incorrectly.","Error!",JOptionPane.OK_OPTION);
    }
    

    Make sure you have the ! before a.equals(b)) since you only want the error to appear when they are not equal.