[英]Populate DefaultTableModel from test file
我有這個文本文件:
A
B
3.00
A
B
3.00
我的觀點是:
我想將每一行與每一列匹配(first_row-first_column、second_row-second_column 等)我在哪里犯了錯誤? 我的代碼如下:
BufferedReader infile = new BufferedReader(reader);
String line = "";
int counter = 0;
String title = "";
String author = "";
String price = "";
try {
while ((line = infile.readLine()) != null) {
++counter;
if (counter == 1) {
title = line;
} else if (counter == 2) {
author = line;
} else if (counter == 3) {
price = line;
SimpleBook sb = new SimpleBook(title, author, price);
bookList.add(sb);
counter = 0;
}
}
} catch (IOException ex) {
Logger.getLogger(SimpleBookList.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
您可以這樣做,因為您的輸入文件中有一個空行。
BufferedReader infile = new BufferedReader(reader);
String line = "";
int counter = 0;
String title = "";
String author = "";
String price = "";
try {
while ((line = infile.readLine()) != null) {
if(line.isEmpty())
continue;
++counter;
if (counter == 1) {
title = line;
} else if (counter == 2) {
author = line;
} else if (counter == 3) {
price = line;
SimpleBook sb = new SimpleBook(title, author, price);
bookList.add(sb);
counter = 0;
}
}
} catch (IOException ex) {
Logger.getLogger(SimpleBookList.class.getName()).log(Level.SEVERE, null, ex);
}
您的計數器在循環開始時遞增,因此您在 if 語句中永遠不會有 0 而是 1。 然后空行被解析為 1 並轉到 A 列。 您可以通過多種方式解決它,例如跳過空行或如果行不為空則增加計數器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.