【问题标题】:Storing data in a multidimensional array将数据存储在多维数组中
【发布时间】:2019-08-08 11:36:42
【问题描述】:

我将此数据存储在 10x5 矩阵中,但是当我到达第一行的 4 位置时,出现此错误“Exception in thread”AWT-EventQueue-0 “java.lang.ArrayIndexOutOfBoundsException: 5”。我认为错误在 listPatients[0][counter] 但我不知道该怎么做。

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

【问题讨论】:

  • 您没有检查计数器是否超过数组长度,即 5。因此,如果调用此方法的次数超过此值,它将始终生成 ArrayOutOfBoundsException

标签: java arrays swing multidimensional-array


【解决方案1】:

10x5 矩阵意味着您可以使用 [0-9][0-4] 中的数组索引。这就是您收到 IndexOutOfBound 异常的原因。 您正在尝试访问listPatients[0][5]。第二个索引值为 5,不可用。该数组任何一行的最后一个索引是listPatients[0-9][4]

检查您的计数器值,因为不知何故它是 5。在访问该数组的任何索引之前修复此值或验证此值。

【讨论】:

  • @Thomas 使用 listPatients[0][4] 。这是告诉索引listPatients [0-9] [4] 的一般方式。
  • 有没有办法让它只在柜台上工作?
  • @ThomasCaycedoMartinez 不,因为它是一个二维数组。如果您想只获得一名患者,则必须指定这两个索引。如果您想获得单个患者数组,那么您将通过Patient[] singleList =listPatients[0] 获得;
猜你喜欢
  • 1970-01-01
  • 2016-07-10
  • 2011-06-10
  • 1970-01-01
  • 2015-11-24
  • 2015-12-08
  • 2013-09-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多