【发布时间】:2017-02-25 01:57:30
【问题描述】:
相当简单的问题,但我基本上得到了调试代码,我已经修复了除一个以外的所有错误。在尝试使程序更友好并包含错误处理时,我发现即使满足条件(即用户搜索的数组中的数字实际上存在于数组中)也会抛出错误消息。不是在寻找直接的答案,只是一个提示。我尝试过使用 if/else 的组合以及在花括号周围移动。
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer to find: ");
try {
int number = input.nextInt();
int index = Arrays.binarySearch(array, number);
for (int i = 0; i < array.length; i++) {
if ( array[i] == number )
System.out.println("Found " + number + " at index " + index++);
}
System.out.printf("Your number was not found within the array.");
}
catch (InputMismatchException e){
System.out.printf("Sorry, but it looks like you entered something other than an integer. Please try again.");
}
}
控制台输出示例:
Enter an integer to find: -9
在索引 0 处找到 -9
在数组中找不到您的号码。
【问题讨论】:
-
当
array中的第一个条目不是正确的数字时,您认为会发生什么? -
只需在 else 子句中打印错误消息。不要抛出异常。
-
@tkausl 嗯,所以它只检查数组中的第一个数字吗?
-
@Jecoms 这有所帮助,但该消息重复了很多次。
-
循环的目的是什么?如果索引存在,则您已经使用二进制搜索数组函数获取索引。如果
index为-1,则找不到您的号码。
标签: java arrays exception error-handling