如果有学生证,我可以打印一条消息,但是如果找不到ID,我只想打印一次println
。
以下是我删除学生的代码
public void removeStudent(int studentId) {
for (int i = 0; i < students.size(); i++) {
if (students.get(i).getId() != studentId) {
continue;
}
System.out.println("Deleted a profile containing information for ID#: " + studentId + ".");
this.students.remove(i);
students = new ArrayList<>();
return;
}
}
答案 0 :(得分:1)
为什么不在java.util.List中使用任何方法? 我的意思是,如果我必须编写一种删除一个(或重复)ID并打印内容的方法,那么我会写这样的内容
public void removeStudent(int studentId) {
if( students.contains(studentId)) {
students.removeIf(id -> id==studentId);
System.out.println("Deleted a profile containing information for ID#: " + studentId + ".");
}
else
System.out.println("nothing to delete");
}
但是,如果您不想将代码更改太多,可以执行以下操作
public void removeStudent(int studentId) {
for (int i = 0; i < students.size(); i++) {
if (students.get(i).getId() != studentId) {
continue;
}
System.out.println("Deleted a profile containing information for ID#: " + studentId + ".");
this.students.remove(i);
students = new ArrayList<>();
return;
}
System.out.println(" Id not found ");
}
我很确定Stream可以使工作比这2个片段更顺利
BR
答案 1 :(得分:0)
根据蒂姆的回答,我建议删除break
以删除所有具有相同ID的学生,但只打印一次:
public boolean removeStudent(int studentId) {
boolean removed = false;
for (int i=0; i < students.size(); i++) {
if (students.get(i).getId() == studentId) {
System.out.println("Deleted a profile containing information for ID#: " + studentId + ".");
this.students.remove(i);
removed = true;
}
}
return removed;
}