java空字符串转数字_java – 将字符串转换为int 如果String为null,则将int设置为0

而不是编写自己的功能使用try-catch的inbuild构造。你的问题是,jsonarray或jsonarray.getJSONObject(i)或值本身是一个null,你调用一个null引用的方法。尝试以下操作:

int block_id = 0; //this set's the block_id to 0 as a default.

try {

block_id = Integer.parseInt(jsonarray.getJSONObject(i).getString("block_id")); //this will set block_id to the String value, but if it's not convertable, will leave it 0.

} catch (Exception e) {};

在Java异常用于标记意外情况。例如,将非数字字符串解析为数字(NumberFormatException)或调用空引用(NullPointerException)上的方法。你可以用很多方法来捕捉它们。

try{

//some code

} catch (NumberFormatException e1) {

e.printStackTrace() //very important - handles the Exception but prints the information!

} catch (NullPointerException e2) {

e.printStackTrace();

}

或使用这个事实,他们都扩展异常:

try {

//somecode

} catch (Exception e) {

e.printStackTrace;

};

或从Java 7开始:

try {

//somecode

} catch (NullPointerException | NumberFormatException e) {

e.printStackTrace;

};

注意

我相信,请仔细阅读答案,请记住,在StackOverflow中,我们需要Minimal, Complete, and Verifiable example,其中包括您的异常的StackTrace。在你的情况下,它可能从以下开始:

Exception in thread "main" java.lang.NullPointerException

那么调试就会容易得多。没有它,它只是猜测。

编辑:根据接受的答案

接受的答案是好的,并且将工作很长时间,因为使用key:block_id存储的值将是数字。如果它不是数字,您的应用程序将崩溃。

代替:

JSONObject jObj = jsonarray.getJSONObject(i);

int block_id = jObj.has("block_id") ? jObj.getInt("block_id") : 0;

应该使用:

int block_id;

try{

JSONObject jObj = jsonarray.getJSONObject(i);

block_id = jObj.has("block_id") ? jObj.getInt("block_id") : 0;

} catch (JSONException | NullPointerException e) {

e.printStackTrace();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值