Comparing two strings with boolean?

29,192

Solution 1

You're doing it backwards. The subject says: if the boolean is true, then do this, else, then do that. So you should program it the same way:

if (isIgnoreCase) {
    return ...
}
else {
    return ...
}

The rest is left as an exercise. You should be able to figure it out by yourself.

Solution 2

I think the requested solution is the following method:

public boolean compareTwoStrings(String a, String b, boolean isIgnoreCase)
{
    if (isIgnoreCase)
    {
        return a.equalsIgnoreCase(b);
    }

    return a.equals(b);
}

Your method das not compile because the Java compiler supposes that unter some circumstances both if conditions evalutes to false. Because of that the compiler can not ensure that at least one return statement is reachable.

Share:
29,192
Kimmm
Author by

Kimmm

Updated on June 14, 2020

Comments

  • Kimmm
    Kimmm almost 4 years

    I was trying this code writing exercise and I am so lost!

    The exercise is:

    Complete the method which takes two Strings and one boolean as input. If the boolean is true, this method compares the first two Strings, ignoring case considerations (uppercase/lowercase). Two Strings are considered equal ignoring case if they are of the same length, and corresponding characters in the two Strings are equal ignoring case.

    If the boolean is false, this method should compare two Strings and return true if the first String represents the same sequence of characters as the second String, otherwise false.

    Note: compareTwoStrings("HELLO", "", false) should return false.

    And here is my attempt:

    public boolean compareTwoStrings (String a, String b, boolean isIgnoreCase) 
    { 
        if (a.equalsIgnoreCase(b)) {
            return (isIgnoreCase==true);
        }
        else if (a.equals(b)) {
           return (isIgnoreCase==false);
        }
    }
    

    It doesn't even compile, but even if it did, I'm sure it wouldn't work.

    • Uku Loskit
      Uku Loskit about 11 years
      you should checking the boolean and first and then be returning the the result of the appropriate method, you've got it in reverse. also, booleans are checked like this if (myBoolean) do something, else do something else