2012-12-03 113 views
1

可以说我有一个返回String的方法。我想检查返回的String是否等于另一个String,并且它们是否相同,以便将返回的String设置为“”。我将如何去做这件事。改变方法的返回值

回答

2

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

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

注意,反正你得回到如果字符串不同,我回来str的东西,但你在这种情况下,我们会知道什么是合适的价值。

0

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

return str.equals("bla") ? "" : str; 
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 = ""; 
} 
+0

谢谢,但返回的字符串是从另一种方法,我打电话给该方法并检查返回的值是否等于我创建的新字符串的值。 – Lock1618