使用数组通过人名线性搜索数字 - 如果名称不存在,方法不起作用

Linear Search for Number via Person's Name Using Array - method not working if name does not exist

我正在尝试使用数组实现线性搜索。它应该搜索一个人的名字,如果名字存在,returning 相应的号码,如果不存在,returning -1。

我为 2 个案例编写了 junit 测试 - 名称存在的地方 (testLinearSearchOK) 和名称不存在的地方 (testLinearSearchFail)。

到目前为止,我只设法使用以下代码使 testLinearSearchOK 通过:

   public class ASearch {


private Entry[] catalogue;
private int current;

/*
 * Assume 10 entries
 */
public ASearch(){
    catalogue = new Entry[10];
    current = 0;
}

/*
 * Ignores adding if full (should really be handled by exception...)
 */
public void addEntry(Entry e){
    if(current < 10){
        catalogue[current++] = e;
    }
}

public int linearSearch(String name){
    int current = 0;

    while (!catalogue[current].getName().equals(name))
        current++;
    return catalogue[current].getNumber();  
}
} 

getName 和 getNumber 方法只是 return 名称和号码。

以下是我编写的测试:

@Before
public void setup(){
    as = new ASearch();
    as.addEntry(new Entry("Pete",111));
    as.addEntry(new Entry("Ken",123));
    as.addEntry(new Entry("Tim",222));
}

@Test
public void testLinearSearchOK() {
    assertEquals(123, as.linearSearch("Ken"));
}

@Test
public void testLinearSearchFail() {
    assertEquals(-1, as.linearSearch("Leo"));
}  

关于如何使 testLinearSearchFail 也能正常工作的任何提示?

来自 Eclipse 的堆栈跟踪(Nicholas 的回答):

java.lang.NullPointerException
at ASearch.linearSearch(ASearch.java:29)
at ASearchTest.testLinearSearchFail(ASearchTest.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access[=12=]0(ParentRunner.java:58)
at org.junit.runners.ParentRunner.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)

跟踪数字而不是索引:

int number = -1;

for(int i = 0; i < catalogue.length; i++) {
    if(catalogue[i].getName().equals(name)) {
        number = catalogue[i].getNumber();
        break;
    }
}

return number;

避免使用多个 returns,当您尝试分析方法的作用时,这是噩梦。

int linearSearch(String name) {
    int result = -1;

    for (CatalogueEntry entry : catalogue) {
        if (name.equals(catalogue.name()) {
            result = catalogue.getNumber();
            break;
        }
    }
    return result;
}

将您的代码更改为:

public static int linearSearch(String name) {
    for (int i = 0; catalogue[i] != null; i++) {
        if (name.equals(catalogue[i].getName())) {
            return catalogue[i].getNumber();       // <--- return early if match found
        }
    }
    return -1;                                     // <--- return -1 for no match 
}

逻辑:

  • 如果名字匹配我们return那个号码
  • 如果没有匹配,那么我们 return a -1

您的代码失败的原因是,即使您没有找到匹配项,您也会尝试 return 数组 catalogue.

中的一个数字