java - 在数组搜索中找不到用于打印用户输入的 if 语句

标签 java arrays if-statement

试图找出一种方法,当用户输入一个不在数组中的整数时,他们会被告知找不到该整数。一直在寻找不同的实现方法,但我对它如何适合我的代码一无所知,希望不同的眼睛可以帮助他们。

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

关于java - 在数组搜索中找不到用于打印用户输入的 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59421414/

相关文章:

java - Java 中 if/else 循环中的变量问题

java - 线程 "main"java.lang.NoSuchFieldError : INSTANCE in AWS SNS 中出现异常

C++ : memory management

Java - 在矩阵行或列上应用 vector 方法

c - 设置为零二维数组(和其他)

javascript - 在nodejs中检查null仅得到 "Cannot read property ' 1' of null"

java - ArrayList 上使用的流 API 减少未同步

java - JVM TI 的链接库名称

java - 电子邮件 mime 解析

php - 去除php中的重复