我有這個方法,它將搜索LinkedList(名爲ListNode)並檢查字符並檢查它們是否包含大寫字符,然後將其存儲在新鏈接列表中,然後返回該字符串。我爲它編寫了代碼,使用JUnit進行了測試,但是它失敗了JUNit(在那些藍色框中)。有誰知道出了什麼問題?LinkedList方法的JUnit測試失敗,爲什麼?
這裏是我的LinkedList方法:
public static ListNode copyUpperCase(ListNode head) {
ListNode newListNode = mkEmpty();
if(head == null){
throw new ListsException("");
}else{
while(head.next != null){
if(Character.isUpperCase(head.element)){
newListNode.element = head.element;
}
head = head.next;
}
}
return newListNode;
}
這裏是ListNode:
public class ListNode {
public char element;
public ListNode next;
}
這裏是測試方法:
@Test
public void testCopyUpperCase()
{
// Inject upper case letters randomly in the test strings.
// Assert equal results when extracting the upper case chars from
// the corresponding list, as wheen extracting them from the
// injected string itself.
for (String s : cases) {
String uppersAndLowers = randInjectUpper(s);
// Extract the upper case characters
StringBuilder uppers = new StringBuilder();
for (int i = 0; i < uppersAndLowers.length(); i++) {
final char c = uppersAndLowers.charAt(i);
if (Character.isUpperCase(c))
uppers.append(c);
}
ListNode temp = Lists.toList(uppersAndLowers);
ListNode lhs = Lists.copyUpperCase(temp);
assertFalse(hasSharedNodes(temp,lhs));
ListNode rhs = Lists.toList(uppers.toString());
assertTrue(Lists.equals(lhs,rhs));
}
}
在TestMethod的失敗行是最後,它是:
assertTrue(Lists.equals(lhs,rhs));
這是什麼意思,如果它在該行失敗?
ps。這裏是equals方法也:
// Two lists are equal if both are empty, or if they have equal lengths
// and contain pairwise equal elements at the same positions.
public static boolean equals(ListNode l1,ListNode l2) {
if (isEmpty(l1) && isEmpty(l2))
return true;
else if (isEmpty(l1) || isEmpty(l2))
return false;
else { // both lists are non-empty
ListNode p1 = l1.next, p2 = l2.next;
while (p1 != null && p2 != null) {
char c1 = p1.element, c2 = p2.element;
if (p1.element != p2.element)
return false;
p1 = p1.next;
p2 = p2.next;
}
return p1 == null && p2 == null;
}
}
編輯:這是新方法:
public static ListNode copyUpperCase(ListNode head) {
ListNode newListNode = mkEmpty();
if(head == null){
throw new ListsException("Lists: null passed to copyUpperCase");
}else{
String cpy = toString(head);
char[] chry = cpy.toCharArray();
for(int i = 0; i < chry.length ; i++)
if(Character.isUpperCase(chry[i])){
newListNode.element = chry[i];
}
newListNode = newListNode.next;
}
return newListNode;
}
我認爲while循環copyUpperCase如果沒有到最後一個項目複製到其他目錄。 –