1

Lets say that I have a method that returns a String. I want to check if the returned String is equal to another String and if they are the same to set the returned String to be just "". How would I go about doing this.

4

3 回答 3

2

假设“原始”字符串是str,“其他”字符串是anotherStr

return str.equals(anotherStr) ? "" : str;

请注意,无论如何,如果字符串不同,你必须返回一些东西,我正在返回str,但你会知道在这种情况下返回的适当值是什么。

于 2012-12-03T01:24:54.487 回答
0

用于String.equals()比较 Java 中的两个字符串。

return str.equals("bla") ? "" : str;
于 2012-12-03T01:25:14.350 回答
0

像这样设置您的check()方法,在其中传入String您要检查的内容,并在方法结束时运行它...

public String check(String comparison){
    // do some normal processing here, which ends up with a String 'result' that you want to return
    ...

    // Do the check at the end
    if (result.equals(comparison)){
        return "";
    }
    else {
        return result;
    }
}

或者,您可以将检查添加到方法调用本身中,这不需要您更改方法的签名......

String result = runMethod();
if (result.equals(comparison)){
    result = "";
}
于 2012-12-03T01:25:56.810 回答