Create a Java program with a method that searches an integer array for a specified integer value (see help with starting the method header below). If the array contains the specified integer, the method should return its index in the array. If not, the method should throw an Exception stating "Element not found in array" and end gracefully. Test the method in main with an array that you make and with user input for the "needle".

Respuesta :

ijeggs

Answer:

The complete program (with the main method) is given in the explanation section below:

Explanation:

public class num2 {

//Main method

   public static void main(String[] args) {

       String[] array = {"Davod", "James", "Oshey", "needle", "balic"};

       String userInput = "ba";

       //Calling the search method

       int returnedIndex = search(array, userInput);

       if (returnedIndex == 0) {

           System.out.println("Element not found in array");

       } else {

           System.out.println("Element found at index " + returnedIndex);

       }

   }

// Method to search the Array

   public static int search(String[] strArray, String value) {

       int index = 0;

       for (int i = 0; i < strArray.length; i++) {

           if (strArray[i].equalsIgnoreCase(value)) {

               index = i;

               break;

           }

       }

       return index;

   }

}

ACCESS MORE
EDU ACCESS