Home > Software engineering >  How to compare a returned string from a method with another string in the main method?
How to compare a returned string from a method with another string in the main method?

Time:06-10

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

CodePudding user response:

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

  •  Tags:  
  • java
  • Related