Java 修改列表';s类成员而不知道其名称
我想要什么我的标题可能不清楚,但我有一个程序,用户可以在其中创建学生(包括姓名、年龄和程序)。在Main()中,用户将收到问题提示,并可以查看当前学生和添加新学生。我想添加修改现有学生的选项,但我不知道在创建学生后如何引用他们 我拥有的 在这里,我创建了一个空列表:Java 修改列表';s类成员而不知道其名称,java,list,class,Java,List,Class,我想要什么我的标题可能不清楚,但我有一个程序,用户可以在其中创建学生(包括姓名、年龄和程序)。在Main()中,用户将收到问题提示,并可以查看当前学生和添加新学生。我想添加修改现有学生的选项,但我不知道在创建学生后如何引用他们 我拥有的 在这里,我创建了一个空列表: public static List<Student> populate(){ List<Student> students = new ArrayList<Student>();
public static List<Student> populate(){
List<Student> students = new ArrayList<Student>();
return students;
}
公共静态列表填充(){
List students=new ArrayList();
留学生;
}
当用户希望在循环中添加学生时,main调用此方法
public static void addStudents(List<Student >students){
int Answer = 1;
while ( Answer == 1){
Scanner reader = new Scanner(System.in);
//not shown: user enters student's name (NewName) age (NewAge) and program (NewProgram)
Student nextStudent = new Student(NewName);
students.add(nextStudent);
nextStudent.age = NewAge;
nextStudent.program = NewProgram;
System.out.println("Do you want to add another student? Press 1 for yes and 2 for no.");
Answer = reader.nextInt();
}
}
publicstaticvoidaddstudents(Liststudents){
int-Answer=1;
while(答案=1){
扫描仪阅读器=新扫描仪(System.in);
//未显示:用户输入学生姓名(新姓名)、年龄(新年龄)和课程(新课程)
学生nextStudent=新学生(新姓名);
学生。添加(下一个学生);
nextStudent.age=NewAge;
nextStudent.program=NewProgram;
System.out.println(“是否要添加其他学生?按1表示是,按2表示否”);
答案=reader.nextInt();
}
}
我所知道的
当我知道学生的名字时,我知道如何更改学生的属性。例如,当我创建一个学生并添加他的年龄时,例如,我写
nextStudent.age=NewAge代码>
但是,由于在填充我的列表后,它们都被称为NextStudent
,因此我不确定如何选择特定的学生并更改其属性。您首先需要编写一个方法,该方法将从与名称(或任何其他内容)匹配的列表中返回学生对象,例如
public Student findByName(列出学生,字符串名称){
用于(学生:学生){
if(student.getName().equals(name)){
留学生;
}
}
返回null;
}
完成此操作后,您可以从editStudent()
方法调用此方法,如果它返回一个对象(即notnull
),您可以执行student.setName(“”
),这将更改名称。
如果它返回null,那么您只需显示一条消息,说明“找不到具有该名称的学生”。students.get().age=NewAge代码>你所说的“然而,自从填充我的列表后,他们都被称为NextStudent”是什么意思?可能错误在于您询问姓名的方式。还要注意的是,您应该将扫描器构造移到循环之外,现在正是开始遵循Java命名约定的好时机。维护一个以名称为键的映射(map
),并按名称选择它们。@Andy Turner.get可能会起作用,但用户如何知道哪个学生是哪个int?我是否应该让所有学生都用旁边的整数命名?在列表中迭代查找具有特定名称的Student
实例。虽然这样做可行,但每次遍历列表检索特定学生在算法上效率很低。对于需要按名称检索的简单情况,您可以使用HashMap而不是列表,对于更复杂的情况,您可以维护单独的索引以快速检索学生。(尽管一旦您想要开始持久化学生数据,您可能可以将该任务委托给您的数据存储层,无论是适当的数据库还是其他解决方案),但在实际应用程序中,您不应该这样做。没有理由不使用映射
,这可能会将搜索时间缩短到O(1)倍。我建议使用此解决方案,假设名称将由用户提供。现在,它可能不匹配的情况下,它可能有一个空间在开始或结束,这将使地图键实现无用。此外,使用这样的方法可以对名称(或任何其他属性)执行智能搜索代码>在开头或结尾有空格怎么样?
public Student findByName(List<Student> students, String name){
for(Student student : students){
if(student.getName().equals(name)){
return student;
}
}
return null;
}