英文:
Double for loop with if condition
问题
我在Java中的双重循环中遇到了问题,具体是内部的if条件。
这是我的代码:
public Set<Term> getAllTermsForStudent(Long id) {
List<Term> terms = termRepository.findAll();
Set<Term> set_terms = new HashSet<Term>(terms); // 有3个学期
Set<Exam> exams = studentService.getStudentExams(id); // 在这个学生的情况下,每个学期有9个考试,每个学期有3个考试
Set<Exam> new_exams = new HashSet<>();
for (Term t : set_terms) {
for (Exam e : exams) {
if (t.getId() == e.getTerm().getId()) { // 考试有学期ID,表示它属于哪个学期,所以我在这里进行比较,并且我想将它添加到新的考试集合中
new_exams.add(e);
}
}
t.setExams(new_exams);
}
return set_terms;
}
这个函数的输出给我每个学期都给了9个考试,就好像它忽略了if条件。
英文:
I am having trouble with double for loop in java, specifically inner if condition
Here is my code:
public Set<Term> getAllTermsForStudent(Long id) {
List<Term> terms = termRepository.findAll();
Set<Term> set_terms = new HashSet<Term>(terms); //there are 3 terms
Set<Exam> exams = studentService.getStudentExams(id); //in this student's case, there are 9 exams, 3 in each term
Set<Exam> new_exams = new HashSet<>();
for(Term t: set_terms) {
for(Exam e: exams) {
if(t.getId() == e.getTerm().getId()) { //exam has term id, which indicates to which
term it belongs, so I'm comparing it, and I
want to add it to new exam set
new_exams.add(e);
}
}
t.setExams(new_exams);
}
return set_terms;
}
Output of this function gives me 9 exams in each term, like it's ignoring if condition
答案1
得分: 3
以下是翻译好的部分:
此函数的输出在每个学期都给了我9场考试,就像忽略了条件一样。
这是因为您在重复使用同一个 Set
来添加考试。
在循环内部声明该变量。
for (Term t : set_terms) {
Set<Exam> new_exams = new HashSet<>();
for (Exam e : exams) {
// ...
}
t.setExams(new_exams);
}
英文:
> Output of this function gives me 9 exams in each term, like it's ignoring if condition
That's because you're reusing the same Set
to add exams to.
Declare the variable inside the loop.
for(Term t: set_terms) {
Set<Exam> new_exams = new HashSet<>();
for(Exam e: exams) {
// ...
}
t.setExams(new_exams);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论