java.lang.NumberFormatException: Invalid int: “” in android

前端 未结 4 1755
感动是毒
感动是毒 2020-11-28 15:58

I already know what is causing this error, I just do not know how to handle the case when a user doesn\'t enter anything into the dialogue box, then hit the button which par

4条回答
  •  暖寄归人
    2020-11-28 16:27

    Problem: How do you check to see if the dialogue box has text in it, before it tries to run the rest of the code.

    Solution: An if statement.

     int parseToInt(String maybeInt, int defaultValue){
         if (maybeInt == null) return defaultValue;
         maybeInt = maybeInt.trim();
         if (maybeInt.isEmpty()) return defaultValue;
         return Integer.parseInt(maybeInt);
     }
    

    If you can spare the extra dependency, I'd pull in Common Lang StringUtils, to use StringUtils.isBlank instead of trim/isEmpty, because that also handles Unicode.

提交回复
热议问题