简体   繁体   中英

Comparing two strings with boolean?

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.

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.

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.

I think this is what you are looking for.

public static void myMethod(String str, String str2, boolean bool) {

    if (bool) {
        str = str.toLowerCase();
        str2 = str2.toLowerCase();
        if (str.equals(str2))
            System.out.println("strings equal");
    }
    else {
        System.out.println("false condition");
    }
}

This could be the solution for your problem:

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

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