0

So I'm trying to make a simple program, for the first JOptionPane Input its asking for the username, then I made an If statement that will print the word "admin" if the String that is attached to the username Input is "admin" However, It's not working and the else statement is executing every time. What am I doing wrong?

import java.util.Scanner;
import javax.swing.JOptionPane;

public class Shipping {

    public static void main(String args[]) {
        String user;
        user = JOptionPane.showInputDialog ("Please enter your username ");
        String pass;
        pass = JOptionPane.showInputDialog ("Please enter your password ");
        if (user == "admin")
            System.out.println ("admin");
        else
            System.out.println("test");
    }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Sag99
  • 3
  • 4
  • Don't compare reference types using `==` or `!=`. Use the `equals(...)` method instead. Understand that `==` checks if the two *object references* are the same which is not what you're interested in. The equals method on the other hand checks if the two references are *functionally equivalent*, and that's what matters here. – Hovercraft Full Of Eels Mar 23 '21 at 17:52
  • Also, code formatting matters. A *lot*. And the rules are not present to force you to make your code look pretty but rather to encourage you to create code that is easier to understand and debug, which your code is neither. You will want to strive to learn and follow these formatting rules, including using indentation appropriately. – Hovercraft Full Of Eels Mar 23 '21 at 17:53
  • I've formatted your code for readability because as I mentioned above, your posted code formatting was not good. In the future, I strongly recommend that you do this yourself. Also, consider putting all if and else blocks within curly braces, since without them, you're at risk of a very hard to debug error. – Hovercraft Full Of Eels Mar 23 '21 at 17:56
  • if (user.equals("admin") System.out.println ("admin"); Would this work? – Sag99 Mar 23 '21 at 18:03
  • Rather than ask, *test*! What happens when you try this (correcting the parenthesis error first, of course)? – Hovercraft Full Of Eels Mar 23 '21 at 18:04
  • Got it finally!! Thank you so much. – Sag99 Mar 23 '21 at 18:06

0 Answers0