我的getFrequency方法用于包的双链表实现

时间:2015-09-07 22:07:09

标签: java

我正在为一个班级做一个双重链接列表包实现,所以任何提示引导我朝着正确的方向都会很棒

这是一些测试代码:

// Adding strings
  String[] contentsOfBag = {"A", "D", "B", "A", "C", "A", "D"};
    testAdd(aBag, contentsOfBag);

  // Tests on a bag that is not empty
  testIsEmpty(aBag, false);
  String[] testStrings2 = {"A", "B", "C", "D", "Z"};
  testFrequency(aBag, testStrings2);
  testContains(aBag, testStrings2);

当在ABCDZ之后测试频率时,会出现这种情况:

Testing the method getFrequencyOf:
In this bag, the count of A is 7
In this bag, the count of B is 5
In this bag, the count of C is 3
In this bag, the count of D is 6
In this bag, the count of Z is 0

Testing the method contains:
Does this bag contain A? true
Does this bag contain B? true
Does this bag contain C? true
Does this bag contain D? true
Does this bag contain Z? false

这是testGetFrequency:

private static void testFrequency(BagInterface<String> aBag, String[] tests)
{
    System.out.println("\nTesting the method getFrequencyOf:");
  for (int index = 0; index < tests.length; index++)
     System.out.println("In this bag, the count of " + tests[index] + 
                        " is " + aBag.getFrequencyOf(tests[index]));
}

我们不应该编辑测试类,我们所做的只是编写方法。

这是我的getFrequencyOf方法:

public int getFrequencyOf(T anEntry) {
    Node current = head;
    int result = 0;

    for(int i = 0; i < numberOfEntries; i++) {
        if(current.data.equals(anEntry))
            result++;
        else
            current = current.next;
    }
    return result;
}

1 个答案:

答案 0 :(得分:0)

无论您是否找到匹配项,您都需要前往下一个条目:

public int getFrequencyOf(T anEntry)
{
    Node current = head;
    int result = 0;

    for (int i = 0; i < numberOfEntries; i++) {
        if (current.data.equals(anEntry)) {
            result++;
        }
        current = current.next;
    }

    return result;
}