【发布时间】: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]。我将如何检查整个数组?