Storing data in a multidimensional array

I am storing this data in a 10x5 matrix but when I get to the 4 position of the first row I have this error "Exception in thread" AWT-EventQueue-0 "java.lang.ArrayIndexOutOfBoundsException: 5". I think the error is in listPatients[0][counter] but I do not know what to do.

public class PatientForm extends javax.swing.JFrame {

       Patient[][] patientList;

        int counter;

    public PatientForm() {
        initComponents();

        patientList = new Patient[10][5];

        counter = 0;
    }


  private void btnasignarActionPerformed(java.awt.event.ActionEvent evt) {                                           
            if (counter < listPatients.length) {
            String identification = txtidentification.getText();
            String name= txtname.getText();
            String lastName = txtlastName.getText();
            String eps = txteps.getText();
            boolean type = jrbtipo1.isSelected();
            String diagnosis = txtdiagnostico.getText();

                Patient objPatient = new Patient(identification, name, lastName, eps, type, diagnosis);


                listPatients[0][counter] = objPatient;
                counter++;

                JOptionPane.showMessageDialog(this, "Head" + counter + " Patients.");
            }else {
                JOptionPane.showMessageDialog(this, "Error", "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
}

Upvotes: 0

Views: 51

Answers (1)

Khalid Shah
Khalid Shah

Reputation: 3232

A 10x5 matrix means you can use indexes of the array from [0-9][0-4]. That is why you are receiving an IndexOutOfBound Exception. You are trying to access listPatients[0][5]. The second index value is 5, which is not available. The last index of any row of that array is listPatients[0-9][4].

Check your counter value because it is 5 somehow. Fix this value or validate this value before accessing any index of that array.

Upvotes: 1

Related Questions