4

I am very new to java, and this seems very simple, perhaps I am missing something.

Below is a little bit of my code, what it should do is have the user enter the a password, which is stored in userinput, unfortunately if I type admin which I have it set to == "admin" it will not work, even if I do all caps or all lowercase like I have it.

I even tried pre-setting a variable such as String password = "admin"; and having it set to be if (userinput == password) but that did not seem to work either. Please help!

    }
    public void protect(){
        Scanner input = new Scanner(System.in);
        System.out.println("Enter password: ");
        String userinput = input.nextLine();
        if (userinput == "admin"){
            System.out.println("Correct!");
        } else if (userinput != "admin"){
            System.out.println("Wrong!");
        }
    }
}

Quick summary, no matter what password I type, even if it is "admin" it goes right to wrong.

JAva Newbie
  • 43
  • 1
  • 1
  • 3

1 Answers1

22

You can't compare strings like that. Use .equals() instead:

if(userinput.equals("admin")) { // etc

Why, you ask?

  • == checks to see if the actual object references are the same.
  • equals(...) checks if the two Strings hold the same string (ie the same characters in the same order)
Greg Kopff
  • 15,945
  • 12
  • 55
  • 78
Makoto
  • 104,088
  • 27
  • 192
  • 230