java - 越界异常

标签 java junit junit4

我必须创建一个程序来查找人员列表中的 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));
}

这些是我收到的错误消息 These are the error messages that i get

提前致谢

最佳答案

检查循环

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

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

关于java - 越界异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46539780/

相关文章:

java - JUnit5 是否向后兼容 JUnit4?

java - 推土机映射不适用于嵌套对象

java - 在 Java swing GUI 中将 ActionListener 类添加到多个 JButtons?

java - 关于Java中自增运算符的简单问题

java - 如何编译JUnit测试类?

java - 如何对以下方法进行单元测试

java - JUnit:同时运行测试

Java 机器因 MySQL 结果太大而崩溃。

android - Eclipse 在创建 android junit 测试配置时抛出 java.lang.NullPointerException

java - 如何在 java junit 测试中使用mockito模拟对函数的调用