gpt4 book ai didi

java - 错误处理(Java)

转载 作者:太空宇宙 更新时间:2023-11-04 12:08:56 25 4
gpt4 key购买 nike

相当简单的问题,但我基本上得到了要调试的代码,并且我已经修复了除一个错误之外的所有错误。当试图使程序更加友好并包含错误处理时,我发现即使满足条件(即用户搜索的数组中的数字实际上存在于数组中),也会抛出错误消息。不寻找直接答案,只是一个提示。我尝试过使用 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

Found -9 at index 0
Your number was not found within the array.

最佳答案

Array.binarySearch如果找到该值则返回索引,否则返回-1。

如果index == -1,您可以打印“未找到消息”,而无需进入循环。

否则,如果index > 0,则可以进入循环并迭代数组以查找值匹配的每个索引。

如果您想要一条包含多个匹配项的消息,则这是必需的,因为 binarySearch 将仅返回找到该值的第一个索引。

顺便说一句,binarySearch 要求首先对数组进行排序,否则结果将是不确定的。我不知道这是否是一个问题,因为数组是在示例之外声明的。

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);

if (index > 0) {
for (int i = 0; i < array.length; i++) {
if ( array[i] == number ) {
System.out.println("Found " + number + " at index " + i);
}
}
} else {
System.out.printf("Sorry, your number wasn't found.");
}
}
catch (InputMismatchException e) {
System.out.printf("Sorry, but it looks like you entered something other than an integer. Please try again.");
}

关于java - 错误处理(Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40063420/

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