在if else循环中使用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;      
}

虽然这种方法可以找到索引,但它会引发数组中每个数字的异常,而不是整个数组的一个。并且,如果在数组中找到该数字,则用循环中的确认行替换其中的一行。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.

我如何才能使它在找到数字时仅打印索引行,反之亦然。我觉得这可能与循环有关,但不确定如何防止这种情况。

乔斯·安吉尔·乔治

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

根据您的代码,您正在检查每个元素,如果不匹配,则会引发异常。这是不准确的,因为除非您扫描所有元素,否则无法得出该元素是否不存在的结论。在这种情况下,您可以使用标志来确定是否找到匹配项,并且在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.");
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章