试图弄清楚如何实现一种方法,当用户输入一个不在数组中的整数时,系统会告知他们找不到该整数。我一直在寻找实现的不同方法,但是我对它如何适合我的代码一无所知,希望有一套不同的观点可以帮助他们解决问题。

import java.util.Arrays;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        int[] numbers = new int[]{5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70};

        System.out.print("Enter number you want to search from Array: ");
        int userInput = scanner.nextInt();

        int returnInput = Arrays.binarySearch (numbers, userInput);
        System.out.println("Binary Search found " + userInput +
                " at position " + returnInput);
        /*
        if statement to output user input was not found in array
         */
        System.out.println("Number entered was not found.");


    }
}

最佳答案

int[] numbers = new int[]{5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70};

System.out.print("Enter number you want to search from Array: ");
int userInput = scanner.nextInt();

int returnInput = Arrays.binarySearch(numbers, userInput);
if (returnInput >= 0)
    System.out.println("Binary Search found " + userInput +
            " at position " + returnInput);
/*
if statement to output user input was not found in array
 */
else
    System.out.println("Number entered was not found.");


此方法返回搜索键的索引(如果它包含在数组中),否则返回(-(插入点)-1)。

09-26 04:06