Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Scanner String Input If statement not working [duplicate]

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.

like image 306
JAva Newbie Avatar asked Nov 29 '22 02:11

JAva Newbie


1 Answers

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)
like image 92
Makoto Avatar answered Dec 04 '22 15:12

Makoto