gpt4 book ai didi

java - 在 if else 循环中使用 try-catch

转载 作者:搜寻专家 更新时间:2023-10-31 08:25:28 25 4
gpt4 key购买 nike

所以我正在制作一个程序,它从命令行获取一个 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.

我怎样才能让它在找到数字时只打印索引行,反之亦然。我觉得这可能与循环有关,但不确定我能做些什么来防止这种情况发生。

最佳答案

searches the array in the program for the int and if found, return the index of the number. If not, then it throws an exception stating that it wasn't found and end the program.

仔细阅读你写的内容。

如果没有找到,你应该抛出一个异常。一旦你遍历了它的所有元素,你只知道你还没有找到值(value)。所以你不能从循环内部抛出。如果您还没有找到该元素,则只能在循环之后抛出。

其次,您应该抛出异常。您没有这样做:相反,您抛出并捕获了刚刚抛出的异常。抛出异常的目的是让方法的调用者知道发生了异常情况。您不应该在方法内抛出和捕获异常。

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

关于java - 在 if else 循环中使用 try-catch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38001264/

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