简体   繁体   中英

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");
    }

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM