我正在尝试创建一个对象数组,我在名为 Patient 的类中有一个计数器 (totalNum)
问题是,每当我添加信息时,前一个数组中的信息就会消失,所有数组都将采用新信息的值,关于如何解决这个问题有什么建议吗?
p.s(计数器的增量在此构造函数中) HospitalPatient[Patient.totalNum] = new Patient(ispnMain , 姓名 ,年龄 ,bloodTypeMain);
这是我的代码:代码处于 while 循环中,因此用户将输入一个选择,然后它会询问此信息
for (int j = 0; j < 100; j++) {
hospitalPatient[j] = new Patient();
}
while(choice != 7) {
switch (choice) {
case 1:
System.out.println ("Please Enter the patient's ISPN:" );
String ispnMain = read.next();
System.out.println ("Please Enter the patient's name:" );
String name = read.next();
System.out.println ("Please Enter the patient's Age:" );
int age = read.nextInt();
System.out.println ("Please Enter the patient's Blood Type:" );
String bloodTypeMain = read.next();
hospitalPatient[Patient.totalNum] = new Patient(ispnMain , name ,age ,bloodTypeMain);
hospitalPatient[Patient.totalNum].SetISPN(ispnMain);
hospitalPatient[Patient.totalNum].SetName(name);
hospitalPatient[Patient.totalNum].SetAge(age);
hospitalPatient[Patient.totalNum].SetBloodType(bloodTypeMain);
hospitalPatient[Patient.totalNum].getISPN();
hospitalPatient[Patient.totalNum].getName();
hospitalPatient[Patient.totalNum].getAge();
hospitalPatient[Patient.totalNum].getBloodType();
// other cases here
}
}
最佳答案
您可以切换到ArrayList
并只需调用add(new Patient())
。您将避免因索引不正确和数组大小调整而产生的所有问题。
关于Java 对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27551305/