我有一个存储对象的数组列表,从这些对象的getter我得到字符串值,如下所示
List<abcd> hgfer = (List<abcd>)Getter.rows(jhfile);
for(abcd f: hgfer)
{
String p = f.getFromArea()
如上所示,数组列表和我正在提取的值。现在我必须确保我得到的字符串不是空的加上它应该被修剪,我实现了如下所示:
p.getFromArea().trim().length() > 0
现在有几个getter连接到这个对象,它将返回一个字符串。 对于每个单独的字符串,我必须这样做。我想要创建一个单独的单独方法,它将返回一个布尔值和一个字符串参数 将会通过。例如:
private String validaterow(String g)
{
boolean valid = false;'
try{
**//code to check that should not be empty plus it should be trim one**
}
catch(){}
valid = false;
}
我必须在类
中的某个地方调用此方法List<abcd> hgfer = (List<abcd>)Getter.rows(jhfile);
for(abcd f: hgfer)
{
if (!validaterow(f.getFromArea())
{//customised message
}
else
continue;
现在请告知我怎样才能实现该字符串不应为空加上它 应修剪一个
答案 0 :(得分:1)
您可以尝试这样的事情: -
public boolean isNullOrEmpty(String str) {
return (str == null) || (str.trim().length() == 0);
}
如果您的true
为String
或null
,则empty
将返回false
。
答案 1 :(得分:1)
根据Apache Commons,您可以使用theire方法检查字符串是否为空。
/**
* <p>Checks if a String is whitespace, empty ("") or null.</p>
*
* <pre>
* StringUtils.isBlank(null) = true
* StringUtils.isBlank("") = true
* StringUtils.isBlank(" ") = true
* StringUtils.isBlank("bob") = false
* StringUtils.isBlank(" bob ") = false
* </pre>
*
* @param str the String to check, may be null
* @return <code>true</code> if the String is null, empty or whitespace
* @since 2.0
*/
public static boolean isBlank(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
}
此示例说明了这种方式的原因:
System.out.println(Character.isWhitespace('c')); // false
System.out.println(Character.isWhitespace(' ')); // true
System.out.println(Character.isWhitespace('\n')); // true
System.out.println(Character.isWhitespace('\t')); // true
答案 2 :(得分:0)
试试这个:
private boolean validaterow(String text)
{
try{
return (text == null) || (text != null && text.trim().length() == 0);
}
catch(){}
return false;
}
}
答案 3 :(得分:0)
boolean validateNullString(String str)
{
return (str == null || str.trim().length() == 0);
}
这将验证您的String对象是否为null并为空。
答案 4 :(得分:0)
试试这个:
private boolean validaterow(String g){
boolean isValid = false;
if(g.trim().isEmpty()){
isValid = true;
}
return isValid;
}
如果参数String不为空,则该方法将返回false。
答案 5 :(得分:0)
使用apache.commons.lang中的StringUtils类
If (StringUtils.isNotBlank(yourString)){
isValid = true;
}
这将修剪yourString并检查null或空值。