Searching an Array For an Exact Match in Java

Searching an Array For an Exact Match in Java | In this post, we will discuss searching an array for an exact match in Java. First, let us understand it through an example:-

Example-1:-
String citiesInMichigan[ ] = {“Acme”, “Albion”, “Detroit”, “Watervliet”, “Coloma”, “Saginaw”, “Richland”, “Glenn”, “Midland”, “Brooklyn”};
String to search:- Glenn
The given string Glenn is present in the citiesInMichigan.

Example-2:-
String fruits[ ] = {“apple”, “mango”, “banana”, “cherry”, “strawberry”, “muskmelon”, ” watermelon”}
String to search:- custard apple
The given string custard apple is not present in the fruits.

Program for Searching an Array For an Exact Match in Java

import java.util.Scanner;

public class Main {

   public static void main(String[] args) {
      Scanner scan = new Scanner(System.in);
      String[] cities = { "Bangalore", "Mysore", 
                          "Bhadravati", "Dharwad", 
                          "Belgaum" };
      Boolean found = false;

      System.out.print("Enter the city name to find: ");
      String city = scan.nextLine();
      for (int i = 0; i < cities.length; i++) {
         if (cities[i].equals(city)) {
            found = true;
            break;
         }
      }
      if (found) {
         System.out.println("The given city " + 
                city + " is present in the array");
      } else {
         System.out.println("The given city " + 
            city + " is not present in the array");
      }
      scan.close();
   }
}

Output:-

Enter the city name to find: Delhi
The given city Delhi is not present in the array

Enter the city name to find: Bangalore
The given city Bangalore is present in the array

Explanation of the above program for searching an array for an exact match in Java is as follows:-
Step-1:- Import the scanner class as we need to take input from the user
Step-2:- In the main class and main method create an array with the cities.
Step-3:- Take a string input from the user which is to be found in the given array.

Step-4:- Use for loop to check whether the string is present in the array or not, for i is equal to 0 and lesser than cities.length increment i.
Step-5:- If the string equals array[i] increment found.
Step-6:- Else return “the string not found”.

Also see:- How to Find the Runtime of a Java Program

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *