In: Computer Science
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".
starting header
**
public static int returnIndex(int[ ] haystack, int needle) {
import java.util.Scanner;
class ExceptionDemo
{
public static int returnIndex(int[ ] haystack, int needle)throws
Exception
{
for(int i=0;i<haystack.length;++i)
{
if(haystack[i]==needle)
return i;
}
throw new Exception("Element not found in array");
}
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
System.out.println("Enter size of array");
int size=input.nextInt();
int[] haystack=new int[size];
System.out.println("Enter elements");
for(int i=0;i<size;++i)
haystack[i]=input.nextInt();
System.out.println("Enter element to search in array");
int needle=input.nextInt();
try
{
System.out.println("Element "+needle+" found at index
"+returnIndex(haystack,needle));
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
Output
koushikhp@koushikhpnew:~$ java ExceptionDemo
Enter size of array
5
Enter elements
10
20
30
40
50
Enter element to search in array
20
Element 20 found at index 1
koushikhp@koushikhpnew:~$ java ExceptionDemo
Enter size of array
5
Enter elements
10
20
30
40
50
Enter element to search in array
12
Element not found in array