【问题标题】:java.lang.ArrayIndexOutOfBoundsException: 1 >= 1java.lang.ArrayIndexOutOfBoundsException: 1 >= 1
【发布时间】:2018-04-26 21:21:50
【问题描述】:

发生了什么? 第一次运行一切顺利,但如果第二次执行,即使它满足 for 条件也会失败:

private void actualizar_screen(){
        DefaultTableModel tabla = (DefaultTableModel) screen_table.getModel();
        int total_rows = tabla.getRowCount();
        int i=0;
        System.out.println("Total items: "+items);
        System.out.println("Total rows: "+total_rows);
        for(i=0;i<items;i++){
            System.out.println("i = "+i);
            tabla.removeRow(i);
        }
        System.out.println("Removidas "+i+" de items "+items);
}

控制台显示如下

Total items: 1
Total rows: 1
i = 0
Removidas 1 de items 1

Total items: 2
Total rows: 2
i = 0
i = 1

java.lang.ArrayIndexOutOfBoundsException: 1 >= 1

【问题讨论】:

  • 当您删除行时,您的items(或total_rows)计数变为无效(因为您刚刚删除了一个值)。
  • items 设置在哪里?
  • 更改:for(i=0;i&lt;items;i++) 为:for(i=items-1; i &gt;= 0; i--)
  • 当您删除第 0 行时,之前的第 1 行将变为第 0 行。当您尝试删除第 1 行时,没有任何内容可删除。 @alfasin 提出的建议是先删除最后一行,然后向下计数。请尝试一下。
  • 已经工作的朋友,但是当只剩下 1 行想要删除时,它会在线程“AWT-EventQueue-0”中显示错误异常 java.lang.ArrayIndexOutOfBoundsException: 1> = 1

标签: java arrays if-statement jtable conditional


【解决方案1】:

您在循环中遇到问题要删除:

Total items: 2 --> items = 2
Total rows: 2 --> tabla.getRowCount() = 2, row index 0, 1 exist
i = 0 --> then remove row index 0, so tabla.getRowCount() = 1 -> row index 0 exist
i = 1 --> then remove row index 1 --> java.lang.ArrayIndexOutOfBoundsException: index >= length 

要修复您的代码,只需使用tabla.removeRow(0); 删除第一行。 或者使用while循环:

while(i < items) {
    System.out.println("i = "+ i++);
    tabla.removeRow(0);
}

【讨论】:

  • 完美,效果惊人。我理解我的错误,非常感谢您
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-19
  • 1970-01-01
  • 1970-01-01
  • 2023-04-10
  • 2019-03-30
  • 2014-05-20
  • 2018-07-14
相关资源
最近更新 更多