【问题标题】:unable to get all row data from Jtable using for loop.. Giving me last row无法使用 for 循环从 Jtable 获取所有行数据。给我最后一行
【发布时间】:2019-09-23 05:44:38
【问题描述】:

我正在尝试使用 for 循环从我的 Jtable 中获取行数据,但它给出了最后一行。下面是我的代码示例:

String item = null; String qty = null; String price = null;
for (int i = 0; i < table.getRowCount(); i++) {
    String f1 =item.getValueAt(i, 0).toString();
    String f2 =item.getValueAt(i, 1).toString();  
    String f3 =item.getValueAt(i, 2).toString(); 
    item = f1; qty = f2; price =f3;
}
Formatter fd = new Formatter();
System.out.println(fd.format("%-20s %5s %10s", item ,qty ,price ));

【问题讨论】:

  • 您希望得到什么结果?从您发布的代码中,很明显只有最后一个表格行将通过调用方法println() 打印出来。您是否尝试调试您发布的代码?
  • 我想获取for循环外的所有行数据?

标签: java swing for-loop iteration


【解决方案1】:

您在每个循环中为变量itemqtyprice 重新分配新值。因此只有最后一个被打印出来。如果您希望打印每一行的值,请在循环内部中包含打印到控制台代码。

for (int i = 0; i < table.getRowCount(); i++) {
    String f1 = item.getValueAt(i, 0).toString();
    String f2 = item.getValueAt(i, 1).toString();  
    String f3 = item.getValueAt(i, 2).toString(); 
    System.out.println(String.format("%-20s %5s %10s", f1 , f2, f3));
}

另外,String.format(..) 方法对你来说可能更有趣。

【讨论】:

  • 或使用System.out.printf()
【解决方案2】:

尝试移动示例代码的最后两行,使其位于循环内:在结束循环的 } 之前。

【讨论】:

  • 已注意到,但我正在尝试访问 for 循环之外的字符串
  • 也许会提供有关您需要做什么的更多详细信息。正如 O. Jones 所说,将 println 移动到循环内。如所写,您的循环正在遍历每个元素并将其放入变量(项目、数量和价格)中,但不对它们做任何事情。在第一次迭代中,您将获得项目、数量和价格中的第一个条目。在第二个,你得到第二个项目(覆盖第一个)等等。最后,在捕获每个项目并将其覆盖到这 3 个变量中之后,才打印变量,从而仅打印最后一个变量。
  • 如果,当循环结束时,你想要一个包含所有条目的字符串,是时候阅读 StringBuilder 类并使用它了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-20
相关资源
最近更新 更多