關於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);
}
}
}

發佈了28 篇原創文章 · 獲贊 7 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章