java.lang.ArrayIndexOutOfBoundsException:1> = 1

时间:2017-11-14 03:19:46

标签: java arrays if-statement jtable conditional

发生了什么事? 它第一次运行一切顺利,但如果第二次执行它即使遇到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

1 个答案:

答案 0 :(得分:0)

循环中有问题要删除:

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