【问题标题】:Populate DefaultTableModel from test file从测试文件填充 DefaultTableModel
【发布时间】:2020-09-18 00:03:23
【问题描述】:

我有这个文本文件:

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);
        }
    }

}

【问题讨论】:

    标签: java


    【解决方案1】:

    您的计数器在循环开始时递增,因此您在 if 语句中永远不会有 0 而是 1。然后空行被解析为 1 并转到 A 列。您可以通过多种方式解决它,例如跳过空行或如果行不为空则增加计数器。

    【讨论】:

      【解决方案2】:

      您可以这样做,因为您的输入文件中有一个空行。

      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);
          }
      

      【讨论】:

        猜你喜欢
        • 2019-06-23
        • 2018-12-11
        • 2012-05-08
        • 2015-09-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多