Showing posts with label Java Programming Searching Element on array in java passing method in java. Show all posts
Showing posts with label Java Programming Searching Element on array in java passing method in java. Show all posts

Monday, October 25, 2021

Searching an Element in Array and Return true if found in java

 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 Array
      System.out.print("Enter size of Array: ");
      size = input.nextInt();
      System.out.println("\n\n");
      //Declaring and creating an array of specified size
      int[] numbers = new int[size];

      //Take Array elements from user
      for(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 searched
      System.out.print("Enter the Value you want to Search: ");
      int value = input.nextInt();

      // Calling method to find value
      boolean found = findValue(numbers,value);  
      if(found)
         System.out.print("\n " + value + " exists in the Array");  
      else
         System.out.println(value +" does not exist in Array");
   
  }//main

  public static boolean findValue(int[] array, int value){     
      //iterate over each element and print it
      for(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

 

String Array and passing method in java

 In this task, we pass a method and also cover the passing String Array to the method. Code:   import java.util.Scanner; public class String...