gpt4 book ai didi

java - 更新 java 的 arraylist 中的特定记录时出现问题

转载 作者:行者123 更新时间:2023-12-01 21:40:10 24 4
gpt4 key购买 nike

好吧,我编写了一个程序,将患者的信息存储在数组中,然后要求用户输入患者的 ID,根据该 ID,该特定患者的记录将显示在屏幕上。现在我必须更新用户输入 ID 的患者记录,但我不知道要使用哪个语句以及如何使用它。我相信我可以使用添加和删除,但我不太确定。这是我的计划:-就在 if(up==1) 之后,我在思考该怎么做时遇到了问题。

package samplee.java;

import java.util.*;

public class patient$ {

public static void main(String[] args) {
ArrayList<patientss> patient1 = new ArrayList<patientss>();
Scanner src = new Scanner(System.in);
Scanner sc = new Scanner(System.in);
Scanner stc = new Scanner(System.in);
Scanner sdc = new Scanner(System.in);
Scanner update = new Scanner(System.in);
int id, it, num, i;
String name;
int ages;
int id1;
Boolean leave = false;
while (!leave) {
patientss xx = new patientss();
System.out.println("Enter the patient's ID ");
System.out.println("-1 to finish entering");
id = src.nextInt();
if (id != -1) {
xx.setId(id);
}
System.out.println("Enter the patient's name ");
System.out.println("-1 to finish entering");
name = stc.next();
if (id != -1) {
xx.setName(name);
patient1.add(xx);
}
System.out.println("Enter the patient's phone number");
System.out.println("-1 to finish entering");
num = sdc.nextInt();
if (id != -1) {
xx.setNum(num);
patient1.add(xx);
} else {
leave = true;
}//Escape the while loop.
}
System.out.println("Enter the id of a student");
it = sc.nextInt();
patientss tt = new patientss();
for (i = 0; i < patient1.size(); i++) {
tt = patient1.get(i);
if (it == tt.getId())
System.out.println(tt.toString());
break;
}
System.out.println("Enter the id of the student you want to update");
Scanner id11 = new Scanner(System.in);
id1 = id11.nextInt();
int up, id2;
patientss dd = new patientss();
for (i = 0; i < patient1.size(); i++) {
dd = patient1.get(i);
if (id1 == dd.getId()) {
System.out.println("If you want to change the name, type 1");
System.out.println("If you want to change the number, type 2");
System.out.println("If you want to change the id, type 3");
up = update.nextInt();
if (up == 1) {

}
}
}
}
}

是的,这是我的病人类(class):-

package samplee.java;

public class patientss {
int id;
String name;
int num;

public int getNum() {
return num;
}

public void setNum(int num) {
this.num = num;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String toString() {
return name + " " + id + " " + num;
}
}

最佳答案

请考虑使用HashMap<Integer, Patientss>而不是ArrayList<Patientss> 。这样您就可以轻松地通过 ID 查找患者。

HashMap 具有 get 和 put 实现,您可以使用它们来检索和更新对象。

关于java - 更新 java 的 arraylist 中的特定记录时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36601187/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com