双重循环和条件判断

huangapple go评论66阅读模式
英文:

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&lt;Term&gt; getAllTermsForStudent(Long id) {

        List&lt;Term&gt; terms = termRepository.findAll();
        Set&lt;Term&gt; set_terms = new HashSet&lt;Term&gt;(terms); //there are 3 terms
        Set&lt;Exam&gt; exams = studentService.getStudentExams(id); //in this student&#39;s case, there are 9 exams, 3 in each term
        Set&lt;Exam&gt; new_exams = new HashSet&lt;&gt;();

        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&#39;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&lt;Exam&gt; new_exams = new HashSet&lt;&gt;();

  for(Exam e: exams) {
    // ...
  }

  t.setExams(new_exams);
}

huangapple
  • 本文由 发表于 2020年9月2日 04:07:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/63694739.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定