java 在java中将空字符串解析为整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7776661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
parsing empty string to integer in java
提问by Adham
if(jsonArray.getJSONObject(i).get("SECNO").toString()!=null && jsonArray.getJSONObject(i).get("SECNO").toString().trim()!="")
appointment.mSecNo =Integer.parseInt(jsonArray.getJSONObject(i).get("SECNO").toString());
else
appointment.mSecNo = -1;
In the previouse lines, when the value of jsonArray.getJSONObject(i).get("SECNO").toString()
equales to '' it doesn't be caught by the if statement ..
在前几行中,当值jsonArray.getJSONObject(i).get("SECNO").toString()
等于 '' 时,它不会被 if 语句捕获。
and I get this error message .. can't parse '' to integer
我收到此错误消息.. can't parse '' to integer
回答by Jon Skeet
Don't use ==
or !=
to compare strings in Java - it only compares the references, not the contentsof the strings. Also, I doubt that toString
would ever return null. I suspect you want:
不要在 Java 中使用==
或!=
比较字符串——它只比较引用,而不是字符串的内容。另外,我怀疑这toString
会永远返回 null。我怀疑你想要:
Foo x = jsonArray.getJSONObject(i).get("SECNO");
if (x != null && x.toString().trim().length() > 0)
(I don't know what the type of jsonArray.getJSONObject(i).get("SECNO")
would be, hence the Foo
.)
(我不知道jsonArray.getJSONObject(i).get("SECNO")
会是什么类型,因此是Foo
.)
In this particular case I've used length() > 0
to detect a non-empty string - but for more general equality, you'd want to use equals
, so an alternative is:
在这种特殊情况下,我曾经length() > 0
检测过一个非空字符串 - 但对于更一般的相等性,您需要使用equals
,所以另一种方法是:
if (x != null && !x.toString().trim().equals(""))
回答by Dunes
Don't compare Strings with ==
不要将字符串与 ==
See: Java comparison with == of two strings is false?, Java String.equals versus ==
回答by Rosdi Kasim
Why not just,
为什么不只是,
int appointment.mSecNo = -1;
try {
appointment.mSecNo = Integer.parseInt(jsonArray.getJSONObject(i).get("SECNO").toString());
}catch(Exception e) {
log.error(" your error message ");
}