我必须创建一个程序,该程序将在“人员”列表中找到commonDates。

public DateSet commonDates() {
        if (persons.size() >= 2) {
            DateSet Cdates =
persons.get(0).getDateSet().intersection(persons.get(1).getDateSet());
            for (int i = 2; i < persons.size(); i++) {
                Cdates = Cdates.intersection(persons.get(i).getDateSet());
            }
            return Cdates;
        }
        else {
            throw new IllegalArgumentException();
       }
    }


这是交集方法:

public DateSet intersection(DateSet other) {
    DateSet dates2 = (DateSet) other;
    DateSet NewDateSet = new DateSet();
    for(int i = 0; i < dates.size(); i++) {
        if (dates.get(i).equals(dates2.dates.get(i))) {
            NewDateSet.add(dates.get(i));
        }
    }
    return NewDateSet;
}


commonDates的Junit测试看起来像这样

@Test
public void testCommonDates() {
    DatePicker persons = new DatePicker();
    List<Date> dates = new ArrayList<Date>();
    Person P1 = new Person("Joop");
    Person P2 = new Person("Joopie");
    Person P3 = new Person("Jaapie");
    Date D1 = new Date("maandag");
    Date D2 = new Date("dinsdag");
    dates.add(D1);
    persons.addPerson(P1);
    persons.addPerson(P2);
    P1.add(D1);
    P2.add(D1);
    P3.add(D1);
    P1.add(D2);
    assertThat("commonDates should return dates all persons have in common", persons.commonDates(), equalTo(dates));
}


这些是我收到的错误消息
java - 超出范围的异常-LMLPHP

提前致谢

最佳答案

检查循环

for (int i = 2; i < persons.size(); i++) {
                Cdates = Cdates.intersection(persons.get(i).getDateSet());
}


您的for循环变量i从初始值2开始,并且正在递增,而应该在递减,对吗?

07-26 06:03