有时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);
}
}
}