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". public static int returnIndex(int[] haystack, int needle) {
In Java please.
Add comments too!
thank you!
code-
import java.util.Scanner;
public class Main
{ public static int returnindex(int[] haystack , int needle) {
if (haystack == null) {
return -1;
}
int len = haystack.length;
int i = 0;
while (i < len) {
if (haystack[i] == needle) {
return i;
}
else {
i = i + 1;
}
}
return -1;
}
public static void main(String[] args) {
int[] haystack = { 1,2,3,4,5,6 };
Scanner sc = new Scanner(System.in);
int needle = sc.nextInt();
if (returnindex(haystack,needle)>=0){
System.out.println(returnindex(haystack,needle));}
else{
throw new ArithmeticException("Element not found in array");
}
}
}
Step by step
Solved in 2 steps with 1 images