I am trying to make a simple password protected program. The idea is that when you type in the correct password, an "Access Granted" message will appear. If the password is typed incorrectly, the message, "Access Denied", appears. This is run on the If/Else Statements. The problem with my program is that even when I type the correct password into the console, the else statement is still runs.
Despite having no errors, (Besides a Resource Leak) this happens. Here is my code:
import java.util.Scanner;
public class PasswordProtected {
public static void main (String args[]){
Scanner Password = new Scanner (System.in);
String mainpassword, userInput;
mainpassword = ("bob");
System.out.println("Please enter the password to continue.");
userInput = Password.nextLine();
System.out.println("Verifying Password");
if (userInput == mainpassword){
System.out.println("Access Granted");
}else{
System.out.println("Access Denied");
}
}
}
This is what my console produces when the password is correct:
Please enter the password to continue.
bob
Verifying Password
Access Denied
This is what my console produces when my password is wrong:
Please enter the password to continue.
erdtfyhujnikyguj
Verifying Password
Access Denied
Could anyone explain to me why this is happening? Is my code wrong? Could someone perhaps help me fix it?