0
public class StringArray {
    private String strArr[];

    public StringArray(int capacity) {
       strArr = new String [capacity];
    }

    public int indexOf(String s) throws StringNotFoundException {
        for(int i=0;i<strArr.length ;++i) {
            if (strArr[i].equals(s)) {
                return i;
            } else {
                throw new StringNotFoundException();
            }
        }
    }
}

我想要做的是返回我正在寻找的字符串的索引,如果它在数组中,否则抛出异常。

但是 Eclipse 说我必须返回一个 int。

那么我应该将返回类型更改为 void 还是有其他选项?

StringNotFoundException 是我编造的一个自定义异常。

4

6 回答 6

6

这样做

public int indexOf(String s) throws StringNotFoundException {
     for(int i=0;i<strArr.length ;++i) {
         if (strArr[i].equals(s)){
             return i;
         }
     }
     throw new StringNotFoundException();
}
于 2013-12-13T14:26:39.100 回答
4

为什么在这里返回-1?这是代码:

public int indexOf(String s) throws StringNotFoundException {
    for(int i=0; i<strArr.length ;++i) {
        if (strArr[i].equals(s)) {
            return i;
        }
    }
    throw new StringNotFoundException();
}
于 2013-12-13T14:27:08.010 回答
2

您没有找到您正在寻找的事实String不足以证明使用Exception. 这不是一个例外情况,你知道它会发生,你在你的代码中这么说。

您的代码应该反映这一点。您不应该返回自定义值,即为诸如此类的事物添加含义-1,这是不正确的。

有关该主题的更多信息:检索方法应该返回“null”还是在无法产生返回值时抛出异常?

于 2013-12-13T14:25:17.133 回答
2

您需要遍历数组中的每个字符串,并且只有在没有匹配项时才抛出异常。

我认为这就是你想要的:

public int indexOf(String s) throws StringNotFoundException {
        for (int i = 0; i < strArr.length; ++i) {
            if (strArr[i].equals(s)) {
                return i;
            } 

        }
        throw new StringNotFoundException();

    }
于 2013-12-13T14:26:22.540 回答
0

尝试这个..

public int indexOf(String s) throws StringNotFoundException {

       int index = Arrays.binarySearch(strArr ,s);

        if( index > 0)
             return index;
        else
            throw new StringNotFoundException();
    }

你为什么要这样做?.

于 2013-12-13T14:38:41.953 回答
0

怎么样:

/** Returns index of String s in array strArr.  Returns -1 if String s is not found. */
public int indexOf(String s) {
        for(int i=0;i<strArr.length ;++i) {
            if (strArr[i].equals(s)){
             return i;
            }
        return -1;
}

完全避免使用异常。

于 2013-12-13T14:26:46.087 回答