为了账号安全,请及时绑定邮箱和手机立即绑定

如何防止java.lang.NumberFormatException:用于输入字符串:“N/A”?

如何防止java.lang.NumberFormatException:用于输入字符串:“N/A”?

郎朗坤 2019-07-20 14:29:45
如何防止java.lang.NumberFormatException:用于输入字符串:“N/A”?在运行我的代码时,我得到了一个NumberFormatException:java.lang.NumberFormatException: For input string: "N/A"     at java.lang.NumberFormatException.forInputString(Unknown Source)     at java.lang.Integer.parseInt(Unknown Source)     at java.lang.Integer.valueOf(Unknown Source)     at java.util.TreeMap.compare(Unknown Source)     at java.util.TreeMap.put(Unknown Source)     at java.util.TreeSet.add(Unknown Source)`如何防止此异常发生?
查看完整描述

3 回答

?
宝慕林4294392

TA贡献2021条经验 获得超8个赞

"N/A"不是整数。一定要扔NumberFormatException如果您试图将其解析为整数。

解析前检查。或手柄Exception恰到好处。

  1. 异常处理*
try{
   int i = Integer.parseInt(input);}catch(NumberFormatException ex){ // handle your exception
   ...}

或者-整数模式匹配 -

String input=...;String pattern ="-?\\d+";if(input.matches("-?\\d+")){ // any positive or negetive integer or not!
 ...}


查看完整回答
反对 回复 2019-07-20
?
忽然笑

TA贡献1806条经验 获得超5个赞

显然你不能解析N/Aint价值。你可以做下面这样的事情来处理这个问题。NumberFormatException .

   String str="N/A";
   try {
        int val=Integer.parseInt(str);
   }catch (NumberFormatException e){
       System.out.println("not a number"); 
   }


查看完整回答
反对 回复 2019-07-20
?
皈依舞

TA贡献1851条经验 获得超3个赞

做这样的异常处理程序,

private int ConvertIntoNumeric(String xVal){
 try
  { 
     return Integer.parseInt(xVal);
  }
 catch(Exception ex) 
  {
     return 0; 
  }}....int xTest = ConvertIntoNumeric("N/A");  //Will return 0


查看完整回答
反对 回复 2019-07-20
  • 3 回答
  • 0 关注
  • 5152 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信