使用带有if else循环的try-catch

Ave*_*ova 5 java arrays methods command-line try-catch

所以我正在创建一个程序,它从命令行获取一个int输入,然后在程序中搜索int中的数组,如果找到,返回数字的索引.如果没有,那么它会抛出一个异常,说明找不到它并结束程序.这是我到目前为止:

public static void main(String[] args) {

    int[] intArray = {9, 97, 5, 77, 79, 13, 7, 59, 8, 6, 100, 55, 35, 89, 74, 66, 32, 47, 51, 88, 23};
    System.out.println(Arrays.toString(intArray));

    int intArgs = Integer.parseInt(args[0]);

    System.out.println("Your entered: " + intArgs);

    FindNum(intArray, intArgs);
}

public static int FindNum(int[] intArray, int intArgs) {
    for (int index = 0; index < intArray.length; index++){
        try{
            if (intArray[index] == (intArgs))
                System.out.println("Found It! = " + index);
            else 
                throw new NoSuchElementException("Element not found in array.");
        } catch (NoSuchElementException ex){
            System.out.println(ex.getMessage());
        }
    }
    return -1;      
}
Run Code Online (Sandbox Code Playgroud)

虽然这种方法可以找到索引,但它会为数组中的每个数字抛出异常,而不是整个数组只有一个.如果它在数组中找到数字,那么它将用循环中的确认行替换其中一行.66的示例输出:

[9, 97, 5, 77, 79, 13, 7, 59, 8, 6, 100, 55, 35, 89, 74, 66, 32, 47, 51, 88, 23]
Your entered: 66
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Found It! = 15
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点,当它找到数字时,它只打印索引行,反之亦然.我觉得它可能与循环有关,但不知道我能做些什么来防止这种情况.

JB *_*zet 6

在程序中搜索int中的数组,如果找到,则返回数字的索引.如果没有,那么它会抛出一个异常,说明找不到它并结束程序.

仔细阅读你写的内容.

如果没有找到,你应该抛出异常.只有在完成所有元素后,您才知道自己没有找到价值.所以你不能从循环中抛出.如果你没有找到元素,你只能在循环之后抛出.

其次,你应该抛出异常.你没有这样做:相反,你抛出并捕获你刚刚抛出的异常.抛出异常的关键是让方法的调用者知道发生异常的事情.您不应该在方法中抛出并捕获异常.

最后,您的方法应该返回索引.但事实并非如此.它总是返回-1.


Jos*_*rge 4

您可以像下面这样重写代码。

根据您的代码,您正在检查每个元素,如果不匹配,则会引发异常。这是不准确的,因为除非扫描所有元素,否则您无法断定该元素是否不存在。在这种情况下,您可以使用标志来确定是否找到匹配项,并且在 for 循环之后您可以检查标志并引发异常。同样,如果您计划在同一方法中捕获异常,那么您可能根本不需要抛出异常。相反,您可以简单地返回索引或-1,如下所示。

public static int FindNum(int[] intArray, int intArgs) {
   for (int index = 0; index < intArray.length; index++){
        if (intArray[index] == (intArgs)){
            System.out.println("Found It! = " + index);
            return index;
        }
   }
   throw new NoSuchElementException("Element not found in array.");
}
Run Code Online (Sandbox Code Playgroud)