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.
You can't compare strings like that. Use .equals()
instead:
if(userinput.equals("admin")) { // etc
Why, you ask?
equals(...)
checks if the two Strings hold the same string (ie the same characters in the same order)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With