-3

I have some code here that should ask the user to input a 'password' that will be checked in my second class. My issue is that the program won't pass through into the method in my second class (PasswordChecker), how would I fix this? I assume it is something to do with the line:

blnPassword2 = PasswordChecker.PasswordCheck(PasswordGuess);

import java.util.Scanner;

public class PasswordGuesser {

    public static void main(String[] args){
        boolean blnPassword2;
        Scanner keyboard = new Scanner(System.in);
        String PasswordGuess = keyboard.nextLine();
        blnPassword2 = PasswordChecker.PasswordCheck(PasswordGuess);

        if (blnPassword2==true) {
            System.out.println("Password correct");
        }
        else 
            {
            System.out.println("Password incorrect");
        }
    }
}    

public class PasswordChecker {

    public static boolean PasswordCheck(String PasswordGuess){
        boolean blnPassword;
        String StrPassword = "Enter";

        if (PasswordGuess==StrPassword) {
            blnPassword = true;
        }
        else {
            blnPassword = false;
        }
        return (blnPassword);
    }
}

Thank you,

Jason Wren

Jason Wren
  • 35
  • 6

1 Answers1

4

You are comparing the reference location of the objects and not the value. Comparing objects is different from comparing primitive data types (int,long,short,char).

Change the following:

if(PasswordGuess==StrPassword)

To

if(PasswordGuess.equals(StrPassword))

Please read up on doing equality operations here:

http://perso.ensta-paristech.fr/~diam/java/online/notes-java/data/expressions/22compareobjects.html

Jorwin Yau
  • 56
  • 1