我需要清除消息,如果Value的长度不等于零...
所以,我正在尝试这种方式,如下所示......
if (Value.length() == 0)
{
setMessage("Template name not specified");
return false;
}
else
{
setMessage("");
}
这是正确有效的方式还是任何其他方式是可能的?
否则,如果我null为字符串赋值并在中使用它setMessage(),它会起作用吗?
我需要清除消息,如果Value的长度不等于零...
所以,我正在尝试这种方式,如下所示......
if (Value.length() == 0)
{
setMessage("Template name not specified");
return false;
}
else
{
setMessage("");
}
这是正确有效的方式还是任何其他方式是可能的?
否则,如果我null为字符串赋值并在中使用它setMessage(),它会起作用吗?
你可以在这里和那里做一些事情:-
if (Value.trim().length() == 0) { // So that even if "Value" contains spaces, it can be taken as 0
setMessage("Template name not specified");
return false;
}
else {
setMessage(null); // It'll be better to use "null" instead of a blank string. or may be some custom String of your own choice.
return true/false; // You missed this statement as your return is conditional here!
}
String.isEmpty("") = true
String.isEmpty(null) = true
String.isEmpty(" ") = false
String.isEmpty("fix") = false
String.isEmpty(" fix ") = false
""表示字符串为空,这是一个好方法。null也可以指空虚。
您可以使用检查字符串是否为空.isEmpty()
最好的方法是
setMessage(""); // without space between quotes;
它是最快和最有效的方式
我通常遵循的一种方式,
private static final String EMPTY_STRING = "";
setMessage(EMPTY_STRING );
由于它是一条消息,您可能会在某个地方显示它,如果您将其设置为null,它将显示为"null" 最终用户。
另一方面,您可以使用isEmpty 方法进行检查。
这是正确有效的方法吗(setMessage(“”))
是的,它是正确和有效的。
或任何其他确切的方式是可能的......
是的,其他方式也是可能的。但是,这是(IMO)最好的方法。
否则我需要将空值分配给字符串并在 setMessage() 中使用它会好吗?
使用 anull代替 是可能的"",但它的问题是使用消息值的东西需要能够处理 a null。空字符串 ( "") 更容易处理。实际上,在大多数情况下,您不需要处理与""非空消息不同的任何事情。