【问题标题】:Trying to find a number in an array with an input and print if it is not equal to the input [duplicate]尝试在具有输入的数组中查找一个数字,如果它不等于输入则打印
【发布时间】:2021-06-14 18:01:08
【问题描述】:

我正在尝试编写我的程序,以便您可以输入一个数字,然后根据如果输入等于数组中的数字,它将打印:“在数组中找到值 7”。如果该值不在数组中,则应显示“在数组中未找到值 X”。

我只得到在数组中找不到值的输出。我哪里错了?

这是我的代码:

public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        
        int [] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        
        System.out.print("Enter a number you would like to search for: ");
        int num = reader.nextInt();
        
        if (num == array[0]) 
        System.out.println("Value " + num + "is in the array.");
        else
        System.out.println("Value " + num + " was not found in the array"); 
}

【问题讨论】:

  • 您所做的就是检查数组的第一个元素是否等于输入。
  • 啊,我明白了,这是我使 if 语句起作用的唯一方法。我做不到 [0, 10]。我将如何检查整个数组?

标签: java arrays


【解决方案1】:

您的代码将用户的输入与数组的第一个元素(即array[0])进行比较。您需要做的是循环遍历整个数组并将数字与数组的每个元素进行比较。

【讨论】:

    猜你喜欢
    • 2022-01-02
    • 1970-01-01
    • 2013-11-11
    • 1970-01-01
    • 2018-05-25
    • 2020-08-11
    • 1970-01-01
    • 2023-03-10
    • 2018-05-07
    相关资源
    最近更新 更多