[英]Populate DefaultTableModel from test file
I have this text file:我有这个文本文件:
A
B
3.00
A
B
3.00
and my view is:我的观点是:
I want to match each row with each column(first_row-first_column,second_row-second_column, etc..) Where have I made a mistake?我想将每一行与每一列匹配(first_row-first_column、second_row-second_column 等)我在哪里犯了错误? My code is as follows:我的代码如下:
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);
}
}
}
you can do this as there is an blank line in your input file.您可以这样做,因为您的输入文件中有一个空行。
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);
}
Your counter is incrementing at the begining of loop, so you never have 0 but 1 on if statement.您的计数器在循环开始时递增,因此您在 if 语句中永远不会有 0 而是 1。 Then empty line is parsed as 1 and goes to A column.然后空行被解析为 1 并转到 A 列。 You can solve it in multpile ways like skip empty lines or increment counter if line is not empty.您可以通过多种方式解决它,例如跳过空行或如果行不为空则增加计数器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.