英文:
Check if the random number exists in the array
问题
如何使用if语句检查数组中是否存在一个数字?如果存在则打印“found”,否则打印“not found”。以下是我的代码:
for (int i = 0; i < arr5.length; i++)
arr5[i] = (int)(Math.random() * 100000 + 0);
Scanner input = new Scanner(System.in);
// 在这里输入要搜索的随机数字
System.out.print("输入搜索数字:");
int searchKey = input.nextInt();
英文:
How can I check if a number exists in an array using if statement? I'm trying to print "found" if it exists and "not found" otherwise. Here is my code:
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();
答案1
得分: 0
使用数组值的IntStream,检查是否有任何一个值与Scanner提供的值匹配。
arr5[i] = (int)(Math.random()*100000 + 0);
Scanner input = new Scanner(System.in);
// 在这里我将输入我的随机搜索数字
System.out.print("输入搜索关键字:");
int searchKey = input.nextInt();
if (IntStream.of(arr5).anyMatch(val -> val == searchKey)) {
// 找到了
}
英文:
Use an IntStream of the array values and check if any of them match the value provided by the 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
得分: 0
你可以通过使用 for each 循环来实现这一点。
for (int number : arr5) {
if (number == searchKey) {
// 执行你想要的操作
System.out.println("我的关键字在数组中");
break;
}
}
英文:
you can do this by a for each loop.
for ( int number: arr5 ) {
if ( number == searchKey ) {
// do everything you want
System.out.println("my key is in the array");
break;
}
}
专注分享java语言的经验与见解,让所有开发者获益!
评论