简体   繁体   中英

Check if the random number exists in the array

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();

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
} 

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;
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM