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.


我认为这是你正在寻找的。

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");
    }
}
链接地址: http://www.djcxy.com/p/76054.html

上一篇: Java NullPointerException对条件空值检查

下一篇: 比较两个字符串与布尔?