嗨,我试图运行我的函数并测试它认为是 junit 测试,但我不知道为什么我的 junit 测试失败了。我确定我写的函数有效。如果有人想知道,这是家庭作业。
这是测试
@Test
public void test4() {
lst1.removeAll(3);
assertEquals(8, lst1.size());
assertEquals(false, lst1.contains(3));
lst1.removeAll(6);
assertEquals(5, lst1.size());
assertEquals(false, lst1.contains(6));
lst1.removeAll(5);
assertEquals(3, lst1.size());
lst1.removeAll(4);
assertEquals(2, lst1.size());
lst1.removeAll(7);
assertEquals(1, lst1.size());
lst1.removeAll(8);
assertEquals(0, lst1.size());
}
这是代码
public void removeAll( E x ) {
first = first.next;
if (first.data == x ) {
first = first.next;
}
Node curr = first;
Node fut = curr.next ;
while ( fut!= null) {
if (fut.data == x ) {
curr.next = fut.next;
}
curr=curr.next;
fut=fut.next;
}
assert check();
}
建立junit
public class MyListTest {
private MyList<Integer> lst0;
private MyList<Integer> lst1;
private Integer[] a;
@Before
public void setUp() throws Exception {
lst0 = new MyList<Integer>();
a = new Integer[] {3,4,3,5,6,8,6,6,7,5};
lst1 = new MyList<Integer>();
for(Integer x: a) {
lst1.add(x);
}
}
尺寸法
public int size() {
return sz;
}
主要方法
public class MyList<E extends Comparable< E>> implements Iterable<E> {
private Node first;
private int sz;
public MyList() {
first = null;
sz = 0;
assert check();
}
}
检查方法
private boolean check()
{
if (first == null && sz != 0) return false;
if (sz == 0 && first != null) return false;
if (sz == 1 && (first == null || first.next != null)) return false;
if (sz > 1 && (first == null || first.next == null)) return false;
int count = 0;
Node p = first;
while(p != null) {
count++;
p = p.next;
}
if (count != sz) {
System.out.printf("count = %d, sz = %d\n", count, sz);
return false;
}
return true;
}