关于Integer.parseInt(str)报NumberFormatException异常问题

有时String类型的数据转换成Int时会出现NumberFormatException异常,其中可能存在两种情况:

第一种:

int类型存储范围是-2,147,483,648 --2,147,483,647 即 -2^31到+2^31-1,若是转换后超出范围则会出现上述异常。

第二种:被转换的字符串中有空格。举个例子:

其中:stu.setAge(Integer.parseInt(s2[2].trim())); 若不加 .trim() 方法就会出现上述异常,此方法就是去除字符串中的空格。



/**
 * 读取 msg.txt 中的内容,
01#张三#20*02#李四#18*03#王五#22*04#赵六#20*05#田七#21
       分割出每个人的信息,样式如下:
01  张三 20
02  李四 18
。。。。

   通过上面的字符串获取学号,姓名,年龄创建Student类,并将Student类的对
象保存到一个ArrayList集合中, 然后 遍历集合中的数据 通过迭代器
 * @author Administrator
 *
 */
public class No2 {
public static void main(String[] args) throws IOException {
List<Student>list=new ArrayList<>();
File file=new File("D:\\zyp\\material\\msg.txt");

FileReader fr=new FileReader(file);
char cbuf[]=new char[1024];


String str = null;



while ((fr.read(cbuf))!=-1) {
str=new String(cbuf);
System.out.println(str);


}


System.out.println(str);
String s1 []=str.split("[*]");
for (int i = 0; i < s1.length; i++) {
String s2[]=s1[i].split("#");
Student stu=new Student();
stu.setId(Integer.parseInt(s2[0]));
stu.setName(s2[1]);
System.out.println(s2[2]);


stu.setAge(Integer.parseInt(s2[2].trim()));


list.add(stu);
}

fr.close();
Iterator< Student>it=list.iterator();
while (it.hasNext()) {
Student student = (Student) it.next();
System.out.println(student);
}
}
}

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值