如何正确解决这个问题:线程中的异常" AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException:-1

时间:2018-04-23 15:34:33

标签: java if-statement

我不知道如何正确设置,而不会出现

的错误
  

线程中的异常" AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException:-1

int row=table_1.getSelectedRow();
int column=4;                                
// If I put it here I get the error and won't run at all the if below   
// String tableRoCol = table_1.getModel().getValueAt(row, column).toString();                                                   
if (row==-1 ) { 
    JOptionPane.showMessageDialog(null, "Please select a room to continue!");                               
}                               
// If I put it here I get the error after it run    
// String tableRoCol = table_1.getModel().getValueAt(row, column).toString();                               
String tableRoCol = table_1.getModel().getValueAt(row, column).toString();                          
if ( tableRoCol.equals("Booked")) {
    JOptionPane.showMessageDialog(null, "Please select a room that is Free to continue!");                              
} else {
    column =3;                                   
    String tableColRoom = table_1.getModel().getValueAt(row, column).toString();
    System.out.println("THE room ID IS :"+tableColRoom);                                
}                           

1 个答案:

答案 0 :(得分:0)

我不确定我是否理解正确,但我假设您不想执行其余代码,如果是行== - 1,如果是这种情况,只需将其余代码包装在else块中。

int row=table_1.getSelectedRow();
int column=4;                                

if (row==-1 ) { 
    JOptionPane.showMessageDialog(null, "Please select a room to continue!");                               
}
else {
    String tableRoCol = table_1.getModel().getValueAt(row, column).toString();                          
    if ( tableRoCol.equals("Booked")) {
        JOptionPane.showMessageDialog(null, "Please select a room that is Free to continue!");                              
    } else {
        column =3;                                   
        String tableColRoom = table_1.getModel().getValueAt(row,       column).toString();
        System.out.println("THE room ID IS :"+tableColRoom);                                
    }  
}