My code is printing "Element not found in array" as many times as it takes to get to that number in the array why and how do I fix that.
My Assignment:
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) {
My code so far:
import java.util.Scanner;
public class Assignment1 {
public static void main(String[] args) {
int[] haystack = { 4,5,6,7,12,13,15,16,22,66,99,643 };
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number in the array: ");
int needle = sc.nextInt();
returnIndex(haystack,needle);
}
public static int returnIndex(int[] haystack, int needle) {
for (int n = 0; n < haystack.length; n++) {
if (haystack[n] == needle)
return n;
else
System.out.println("Element not found in array");
}
return -1;
}
}
My output:
Enter a number in the array:
7
Element not found in array
Element not found in array
Element not found in array
or
Enter a number in the array:
15
Element not found in array
Element not found in array
Element not found in array
Element not found in array
Element not found in array
Element not found in array
System.out.println("Element not found in array");doesn't belong inside the loop.System.outin theelseblock and check the result after thereturnIndexmethod returns. Handle the result according to your problem description.for (int n = 0; n < haystack.length; n++)you print Element not found in array every time condition(haystack[n] == needle)occurs. Try to replacereturn -1;with it.