Converting a String to int. Set the int to 0 if String is null

前端 未结 12 2205
孤街浪徒
孤街浪徒 2021-01-17 10:09

I have a function which saves Android data in sqlite but I have to convert the String data to an Integer.

Whenever the S

12条回答
  •  Happy的楠姐
    2021-01-17 10:31

    Notice.. you could also write it like that

     public static Integer convertToInt(String str) {
        int n=0;
        if(str != null && str.length()>0) {
            n = Integer.parseInt(str);
        }
        return n;
    }
    

    but the try/catch method is way more effective and simple and will not cause a system exit if a letter get inside the String (just worth mentioning)

    also, it is important to notice that writing the same equation like that:

    if(str != null & str.length()>0) {}
    

    or like that:

    if(str.length()>0 && str != null) {}
    

    can cause the operation to fail because it will try to count the String even if it is null

    Hope I responded to all your questions

提交回复
热议问题