Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to compare a returned string from a method with another string in the main method?

The idea is that the while loop should loop through the code if the result is "wrong password",
until the correct password is entered and breaks the loop when it matches the login method return value.

while (true){
   System.out.println("\nLogin: ");
   System.out.println("\nEnter a username: ");
   String loginUsername = sc.nextLine();
   System.out.println("Enter a password: ");
   String loginPassword = sc.nextLine();
   System.out.println(login(loginUsername,loginPassword));
   if (login(loginUsername,loginPassword).equalsIgnoreCase("Successfully logged in!")) {
       break;
   }
}

this code is the return statements from the login method

if (check == true){
        return ("\nSuccessfully logged in!");
    } else {
        return ("\nWrong username/password");
    }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

But "Successfully logged in!" is not the same string as "\nSuccessfully logged in!".

More importantly… Why use strings for this at all? If you want to know whether something is true or false, there’s a perfectly good data type to convey that information. Return that type instead:

return check;

Rename the method to something more meaningful than login, and use its result in a semantically clear condition:

if (isLoginSuccessful(loginUsername,loginPassword)) {
    break;
}

This puts the semantics of what you’re doing in the code itself, rather than in magic strings that you need to copy/paste everywhere and manually keep track of. Which, already in this one tiny example, you’ve lost track of by making the strings different. (With the added benefit that using booleans for conditional logic probably performs a little better than string comparison.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading