有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java抛出自定义异常(如果为循环)

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


共 (6) 个答案

  1. # 1 楼答案

    那么:

    /** 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;
    }
    

    避免完全使用异常

  2. # 2 楼答案

    试试这个

    public int indexOf(String s) throws StringNotFoundException {
    
           int index = Arrays.binarySearch(strArr ,s);
    
            if( index > 0)
                 return index;
            else
                throw new StringNotFoundException();
        }
    

    你为什么要这么做

  3. # 3 楼答案

    你喜欢这样吗

    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();
    }
    
  4. # 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();
    }
    
  5. # 5 楼答案

    您需要遍历数组中的每个字符串,只有当没有匹配的字符串时,才会抛出异常

    我想这就是你想要的:

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