小编use*_*379的帖子

如果是循环,则抛出自定义异常

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();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

然而Eclipse说我必须返回一个int.

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

StringNotFoundException是我编写的自定义异常.

java arrays for-loop exception custom-exceptions

0
推荐指数
1
解决办法
247
查看次数

标签 统计

arrays ×1

custom-exceptions ×1

exception ×1

for-loop ×1

java ×1