テキストファイルのデータを読み込んで配列に格納する次のコード行を記述しました。 String
をint
に変換しようとした場合を除き、すべて正常に動作します。配列から文字列をintに割り当てることができません
ここでは、テキストファイルを1行ずつスキャンし、すべての単語をコンマで区切って配列に格納しようとしています。私はString
をint
に変換し、それをint id
に割り当てると、なぜその投げ込みがNumberFormatException
になるのか理解できません。
次は私が書いたコードです:
public boolean loadPapers(){
String fileName = "paper.txt"; // file to be opened
boolean fileOpened = true;
int id, rank;
String topic, author, date;
try {
Scanner fileData = new Scanner(new File(fileName));
while(fileData.hasNextLine()){
String line = fileData.nextLine();
String[] words = line.split(","); // Separate words from sentence
// get required parameters for Paper object
id = Integer.parseInt(words[0]); // throws numberFormatException
topic = words[1];
author = words[2];
date = words[3];
rank = Integer.parseInt(words[4]); // throws numberFormatException
// create new paper
Paper entry = new Paper(id, topic, author, date, rank);
paperList.add(entry);
} // end while
fileData.close(); // close file
} // end try
catch (FileNotFoundException e) {
fileOpened = false;
swingErrorMessage("ERROR: File couldn't be opened.\nNo papers were loaded.", "File Error");
} // end catch
return fileOpened;
} // end loadPapers
次は、テキストファイルの内容です:
46,Evolutionary Comp,Michael Smith,12/01/10,4 61,Fuzzy Logic and App,John Peterson,13/01/10,3 118,Neural Networks,Arthur London,20/01/10,5 200,Evolutionary Comp,Scott Jones,30/01/10,1 210,Fuzzy Logic and App,Joe Wang,01/02/10,4 12,Evolutionary Comp,Andy Roberts,12/12/12,3 123,Computer Science,Zhou You,12/12/12,3
プログラムが上の障害が発生した行は次のとおりです。
id = Integer.parseInt(words[0]); // throws numberFormatException
エラーメッセージは次のようになります。
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:470)
at java.lang.Integer.parseInt(Integer.java:499)
at PaperManagerApplication.Frame.loadPapers(Frame.java:409)
at PaperManagerApplication.PaperManager.main(PaperManager.java:16)
あなたは '言葉[0]'と '言葉をプリントアウトしてくださいすることができ[4]私たちは見ることができます'ように、あなたのプログラムが失敗する文字列コンテンツ? – Bringer128
idの出力中にプログラムが失敗し、NumberFormatExceptionがスローされます。 – Subash
配列を分割した後に配列の値を出力することをお勧めします。おそらく答えが素早く見つかるでしょう - 文字列と印刷のIDを残してください。そしてあなたが見るでしょう。 – user710502