2

I wrote a very basic login program in Java recently and I'm doing everything right, but I always get that the username doesn't match.

Here is the program:

public static void main(String[] args) {

        //Creation
        String username = JOptionPane.showInputDialog(null, "Create Username:");
        int password = Integer.parseInt(JOptionPane.showInputDialog(null, "Create Password:\nOBS! Password Must Be Numbers!"));

        JOptionPane.showMessageDialog(null, "Success! Login Created!\nTransferring you to login screen...");

        //Login
        String loginu = JOptionPane.showInputDialog(null, "Username:");
        int loginp = Integer.parseInt(JOptionPane.showInputDialog(null, "Password:"));

        if (username == loginu && password == loginp) {

            JOptionPane.showMessageDialog(null, "Success!");

        }else if (username == loginu && password != loginp) {

            JOptionPane.showMessageDialog(null, "Password doesn't match.");

        }else if (username != loginu && password == loginp) {
            //always end up here!?
            JOptionPane.showMessageDialog(null, "Username doesn't match.");

        }else {

            JOptionPane.showMessageDialog(null, "Something went wrong.");

        }   

    }

}
svens
  • 11,438
  • 6
  • 36
  • 55
tTim
  • 21
  • 2

2 Answers2

1

You should use .equals when comparing strings as they are not primitives but objects. Please see the below code . Refer to this for detailed answer

import javax.swing.JOptionPane;

public class fsdfd {

    public static void main(String[] args) {

        // Creation
        String username = JOptionPane.showInputDialog(null, "Create Username:");
        int password = Integer.parseInt(JOptionPane.showInputDialog(null,
                "Create Password:\nOBS! Password Must Be Numbers!"));

        JOptionPane.showMessageDialog(null,
                "Success! Login Created!\nTransferring you to login screen...");

        // Login
        String loginu = JOptionPane.showInputDialog(null, "Username:");
        int loginp = Integer.parseInt(JOptionPane.showInputDialog(null,
                "Password:"));

        if (username.equals(loginu) && password == loginp) {

            JOptionPane.showMessageDialog(null, "Success!");

        } else if (username.equals(loginu) && password != loginp) {

            JOptionPane.showMessageDialog(null, "Password doesn't match.");

        } else if (!username.equals(loginu) && password == loginp) {
            // You wont end up now
            JOptionPane.showMessageDialog(null, "Username doesn't match.");

        } else {

            JOptionPane.showMessageDialog(null, "Something went wrong.");

        }

    }

}
Community
  • 1
  • 1
Kalyan Chavali
  • 1,330
  • 8
  • 24
0

Use String equals method for comparison instead of ==.

username.equals(loginu) && password.equals(loginp)
Rajesh
  • 2,135
  • 1
  • 12
  • 14