【问题标题】:Check if the random number exists in the array检查随机数是否存在于数组中
【发布时间】:2020-04-05 01:33:27
【问题描述】:
如何使用 if 语句检查数组中是否存在数字?如果存在,我正在尝试打印“找到”,否则打印“未找到”。这是我的代码:
for(int i = 0; i < arr5.length; i++)
arr5[i] = (int)(Math.random()*100000 + 0);
Scanner input = new Scanner(System.in);
// here i will input my search random number
System.out.print("Input search key: ");
int searchKey = input.nextInt();
【问题讨论】:
标签:
java
arrays
linear-search
【解决方案1】:
使用数组值的 IntStream 并检查它们是否与 Scanner 提供的值匹配。
arr5[i] = (int)(Math.random()*100000 + 0);
Scanner input = new Scanner(System.in);
here i will input my search random number
System.out.print("Input search key: ");
int searchKey = input.nextInt();
if (IntStream.of(arr5).anyMatch(val -> val == searchKey)) {
// found
}
【解决方案2】:
你可以通过一个 for each 循环来做到这一点。
for ( int number: arr5 ) {
if ( number == searchKey ) {
// do everything you want
System.out.println("my key is in the array");
break;
}
}