检查随机数是否存在于数组中。

huangapple 未分类评论53阅读模式
英文:

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 &lt; 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(&quot;Input search key: &quot;);
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(&quot;Input search key: &quot;);
int searchKey = input.nextInt();

if (IntStream.of(arr5).anyMatch(val -&gt; 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(&quot;my key is in the array&quot;);
break;
}
}

huangapple
  • 本文由 发表于 2020年4月5日 09:33:27
  • 转载请务必保留本文链接:https://java.coder-hub.com/61036979.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定