将String转换为int.如果String为null,则将int设置为0

Geo*_*off 23 java android

我有一个保存Android数据的功能,sqlite但我必须将String数据转换为Integer.

只要Stringnull我想保存为0

以下是我的代码,只要值是,它就会失败 null

 int block_id = Integer.parseInt(jsonarray.getJSONObject(i).getString("block_id"));
Run Code Online (Sandbox Code Playgroud)

block_id上述转化为Integer.

这是我决定要做的,但它仍然无法将字符串值转换为0它的时间null.

int block_id = Converttoint(jsonarray.getJSONObject(i).getString("block_id"));
Run Code Online (Sandbox Code Playgroud)

然后功能 convertToInt

 public static Integer convertToInt(String str) {
    int n=0;
  if(str != null) {
      n = Integer.parseInt(str);
  }
    return n;
}
Run Code Online (Sandbox Code Playgroud)

我应该如何改变它,让它工作?

Nic*_*tto 24

只需使用内置方法JSONObject#getInt(String),它会自动将值转换为a ,如果它是a,则通过调用int场景,Integer.parseInt(String)如果是a则String通过调用.为了避免在您的密钥不可用时出现异常,只需先检查您的实例是否使用了密钥,这足以保证安全,因为密钥不能具有值,要么存在非值,要么不存在.Number#intValue()NumberJSONObjectJSONObject#has(String)nullnull

JSONObject jObj = jsonarray.getJSONObject(i);
int block_id = jObj.has("block_id") ? jObj.getInt("block_id") : 0;
Run Code Online (Sandbox Code Playgroud)


xen*_*ros 15

而不是编写自己的函数使用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) {};
Run Code Online (Sandbox Code Playgroud)

在Java中,异常用于标记意外情况.例如,将非数字解析为数字String(NumberFormatException)或调用null引用(NullPointerException)上的方法.你可以通过很多方式捕获它们.

try{
    //some code
} catch (NumberFormatException e1) {
    e.printStackTrace()     //very important - handles the Exception but prints the information!
} catch (NullPointerException e2) {
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

或使用这一事实,他们都扩展Exception:

try {
    //somecode
} catch (Exception e) {
    e.printStackTrace;
};
Run Code Online (Sandbox Code Playgroud)

或者从Java 7开始:

try {
    //somecode
} catch (NullPointerException | NumberFormatException e) {
    e.printStackTrace;
};
Run Code Online (Sandbox Code Playgroud)

注意

我相信,你会仔细阅读答案,请记住,在StackOverflow上,我们需要包含异常StackTrace 的Minimal,Complete和Verifiable示例.在您的情况下,它可能从以下开始:

Exception in thread "main" java.lang.NullPointerException
Run Code Online (Sandbox Code Playgroud)

然后,调试更容易.没有它,它只是在猜测.

编辑: 根据接受的答案

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

代替:

JSONObject jObj = jsonarray.getJSONObject(i);
int block_id = jObj.has("block_id") ? jObj.getInt("block_id") : 0;
Run Code Online (Sandbox Code Playgroud)

一个人应该使用:

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();
}
Run Code Online (Sandbox Code Playgroud)


Shw*_*ati 9

除了其他答案中给出的方法之外,还有一种方法可以做到这一点.

String blockId=jsonarray.getJSONObject(i).getString("block_id");
int block_id = blockId==null ? 0 :  Integer.parseInt(blockId);
Run Code Online (Sandbox Code Playgroud)


Amb*_*wal 8

你可以检查一下NumberFormatException.Integer.parseInt()将抛出NumberFormatException案件:

  • Stringnull
  • String是空的("")
  • String无法转换int为任何其他原因(比如说String"aff""1.25")

基本上,它将处理所有可能的非整数情况.

代码示例:

private static int convertStringToInt(String str){
    int x = 0;
    try{
        x = Integer.parseInt(str);
    }catch(NumberFormatException ex){
        //TODO: LOG or HANDLE
    }
    return x;
}
Run Code Online (Sandbox Code Playgroud)


Sac*_*inS 7

你可以使用以下方法,

String id = jsonarray.getJSONObject(i).getString("block_id")
int blockId = getBlockId(id);

@NonNull
private Integer getBlockId(String id) {
    Integer blockId= 0;
    try {
        blockId= Integer.parseInt(id);
    } catch (NumberFormatException e) {
        e.printStackTrace();
    }
    return blockId;
}
Run Code Online (Sandbox Code Playgroud)


Ozz*_*zzz 6

String toBeParsedStr="1234";
int parsedInt=toBeParsedStr!=null&&toBeParsedStr.matches("[0-9]+")?Integer.parseInt(toBeParsedStr):0;
Run Code Online (Sandbox Code Playgroud)


sub*_*ati 6

试试这个

 int block_id = (jsonarray.getJSONObject(i).has(block_id)) ? jsonarray.getJSONObject(i).getInt("block_id") : 0;
Run Code Online (Sandbox Code Playgroud)