gpt4 book ai didi

java - if for 循环抛出自定义异常

转载 作者:行者123 更新时间:2023-12-01 06:30:49 24 4
gpt4 key购买 nike

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 是我编写的一个自定义异常。

最佳答案

这样做

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();
}

关于java - if for 循环抛出自定义异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20568774/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com