【发布时间】:2016-10-26 08:34:14
【问题描述】:
所以我正在制作一个程序,它从命令行获取一个 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.
我怎样才能使它在找到数字时只打印索引行,反之亦然。我觉得这可能与循环有关,但不确定我能做些什么来防止这种情况发生。
【问题讨论】:
-
将循环放在 try-block 内,而不是将 try-block 放在循环内。或者更好的是,为什么还要有一个try-block?只需进行搜索,如果未找到,则打印错误消息。
-
把你的 try-catch 放在 for 循环外面,而不是里面。
-
您每次都抛出异常以检查数组中的元素的值并发现不匹配,这是不正确的,因为只有在访问所有元素后才能断定该元素不在数组中。
-
如果您打算将异常从函数中抛出,为什么要捕获异常?
-
@AvenNova 阅读了我的回答:您根本不应该尝试捕获。你应该抛出一个异常,而不是捕获它。
标签: java arrays methods command-line try-catch