我創建了一個用Java讀取文件的方法。問題文件包含以下格式的書籍列表:姓氏|名字|標題。但是,當我嘗試使用該方法時,我收到一條錯誤消息。我的方法如下:Java - 讀取問題txt.file
private final static char END_SIGN = '|';
void readBookFile(String readFile) {
try {
FileReader textFileReader = new FileReader(readFile);
BufferedReader textReader = new BufferedReader(textFileReader);
int numberOfBooks = Integer.parseInt(textReader.readLine());
for (int i = 0; i < numberOfBooks; i++) {
String post = textReader.readLine();
int index1 = post.indexOf(END_SIGN);
int index2 = post.indexOf(END_SIGN, index1 + 1);
String lastname = post.substring(0, index1);
String firstname = post.substring(index1 + 1, index2);
String title = post.substring(index2 + 1);
Book book = new Book(lastname, firstname, title);
addBook(book);
}
tekstReader.close();
}
catch (IOException exception) {
System.out.print("Wrong file reading: " + exception);
System.exit(1);
}
}
當我試圖運行這個方法我收到錯誤消息:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Twain|Mark|The Adventures of Huckleberry Finn"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Library.readBookFile(Library.java:36)
at LibraryTest.main(LibraryTest.java:8)
36行是我找出整數NUMBEROFBOOKS方法的一部分。所以顯然這不是出於某種原因。如果有人知道可能會導致這種情況,我將不勝感激!
5個答案在60秒內。哇。 –
建議:永遠不要在默認包中放置任何類。總是把你的類放在一個定義良好的包中(package com.yourcompany.yourproject.somepackage)。 –
也許你會想在開頭添加行數作爲自己的行? –