0

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();
Hollis Waite
  • 1,079
  • 1
  • 20
  • 31
  • Does this answer your question? [Java, Simplified check if int array contains int](https://stackoverflow.com/questions/12020361/java-simplified-check-if-int-array-contains-int) – Doi9t Apr 05 '20 at 01:38

2 Answers2

0

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
} 
Jason
  • 5,154
  • 2
  • 12
  • 22
0

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;
}
}
hamidreza75
  • 567
  • 6
  • 15