In this task pass the Array to a method and search an Element in Array and Return true if found in java. we use the Scanner method and search the element in Array.
Code:
import java.util.Scanner;public class SearchingElement{public static void main(String[] args){Scanner input = new Scanner(System.in);int size;// Size of ArraySystem.out.print("Enter size of Array: ");size = input.nextInt();System.out.println("\n\n");//Declaring and creating an array of specified sizeint[] numbers = new int[size];//Take Array elements from userfor(int i=0; i<size; i++){System.out.print("Enter value for numbers[" + i + "] = ");numbers[i] = input.nextInt();System.out.println("\n\n");}//Value to be searchedSystem.out.print("Enter the Value you want to Search: ");int value = input.nextInt();// Calling method to find valueboolean found = findValue(numbers,value);if(found)System.out.print("\n " + value + " exists in the Array");elseSystem.out.println(value +" does not exist in Array");}//mainpublic static boolean findValue(int[] array, int value){//iterate over each element and print itfor(int i = 0; i < array.length; ++i){if(array[i] == value){return true;} }return false;}}//class
Code:
| Searching an Element in Array and Return true if found in java |