嘿,所以我試圖從文本文件中讀取值,以便我可以使用它的其他東西 - 但是,我不斷收到'lava.lang.NumberFormatException'時我嘗試跑步。這是我的代碼的一小部分,問題似乎在於此。在Java中讀取文件時的數字格式異常
public void readData(String fileName) {
try {
Scanner in = new Scanner(new File(fileName));
String[] line;
int mid; //user-id
int uid; //isbn
int rating; //book rating
//int start =0;
//String date;
//System.out.println(in.nextLine());
in.nextLine();
while(in.hasNextLine()) {
//if(start != 0){
line = in.nextLine().split(";");
System.out.println(line[0].trim().replace("\ufeff", "") + " length: "+ line[0].length());
//System.out.println(line[0]+ " -----------++++++++++++++");
mid = Integer.parseInt(line[0].trim());
uid = Integer.parseInt(line[1].trim()); //isbn change
rating = Integer.parseInt(line[2].trim());
addToMovies(mid, uid, rating);
addToCust(mid, uid, rating);
//} //else {
//start ++;
}
//}
}
catch(FileNotFoundException e) {
System.out.println("Can't find file " + fileName);
e.printStackTrace();
}
catch(IOException e) {
System.out.println("IO error");
e.printStackTrace();
}
這是我將讀取數據:
"User-ID;""ISBN"";""Book-Rating"""
"276725;""034545104X"";""0"""
"276726;""0155061224"";""5"""
"276727;""0446520802"";""0"""
"276729;""052165615X"";""3"""
"276729;""0521795028"";""6"""
"276733;""2080674722"";""0"""
"276736;""3257224281"";""8"""
"276737;""0600570967"";""6"""
"276744;""038550120X"";""7"""
當我運行它,我得到以下錯誤:
"276725 length: 7
usage: java MemReader sourceFile destFile
java.lang.NumberFormatException: For input string: ""276725"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at memreader.MemReader.readData(MemReader.java:76)
at memreader.MemReader.main(MemReader.java:265)
這樣看來,也許是java因爲我已經通過打印第一個索引的長度來測試它,並且字符的數量超過了應該存在的字符數。任何幫助都感激不盡。
是'「」276725「'是一個數字嗎?我的意思是,如何清除你想要的異常? – Rishav
你試圖解析字符串'」「276725」'(帶引號!),就好像它是一個數字。不是;您需要先刪除引號。 – Jesper
實際上我正在以csv格式讀取文件,而那些引號不在那裏。我在記事本中打開它,以便我可以複製和粘貼數據。 – user2035796