Java中String转int类型出现的问题及解决方式

一般在Java中String转为Int主要有两种方法:
1. Integer.parseInt(str);
2. Integer.valueOf(str);

ps:两者的不同之处:
Integer.parseInt(s)返回值为Int型
Integer.valueOf(s)返回值为Integer,区别在于后者能够使用Integer的一些方法。


转换出现问题时,一般是报NumberFormatException:
1) 输入为空时
2) 输入为字母时,如abcd等,不为数字的情况时
3) 输入超出int上限时


针对情况1)可以做判断是否为空;
针对情况2)可以做正则表达式校验;
针对情况3)可以用try-catch;
可以通过try-catch作出相应的友好提示:

try{
    if(StringUtils.isEmpty(str)){
        System.out.println("不能为空");
    }
    attern pattern = Pattern.compile("[0-9]*"); 
    Matcher isNum = pattern.matcher(str); 
    if( !isNum.matches() ){ 
        System.out.println("必须为数字");
    }
    Integer i = Integer.valueOf(str);
}catch(NumberFormatException e){
    System.out.println("超过上限");
}

对于情况3),可能有一种情况必须要转为int类型,比如时间转为时间戳,由13位的时间戳字符串转为int类型,可能有超过上限的情况,处理方法可以通过String转为Long,处理之后,再转为int。

String timeStr = "1527498005000";
Long timeLong = Long.parseLong(timeStr )/1000;
Integer timeInt = timeLong.intValue();

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值