0

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
3
  • HINT: System.out.println("Element not found in array"); doesn't belong inside the loop. Commented Jun 26, 2017 at 3:13
  • Remove the System.out in the else block and check the result after the returnIndex method returns. Handle the result according to your problem description. Commented Jun 26, 2017 at 3:13
  • In your for (int n = 0; n < haystack.length; n++) you print Element not found in array every time condition (haystack[n] == needle) occurs. Try to replace return -1; with it. Commented Jun 26, 2017 at 3:14

4 Answers 4

2

You are getting same output multiple times as you are not breaking out of loop.Also if element is not there in array only if you have iterate through the entire array, so move System.out.println("Element not found in array"); outside the for loop. Below is the complete example, have a look.

user below code where i am breaking the loop if element is not found in the array.

public class SOTest {
    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();
        int index = returnIndex(haystack, needle);
        if(index!=-1) // print index only if element is in array.
        System.out.println("Element found at index : " + index);

    }

    public static int returnIndex(int[] haystack, int needle) {
        for (int n = 0; n < haystack.length; n++) {
            if (haystack[n] == needle)
                return n;
        }
        System.out.println("Element not found in array");
        return -1;

    }
}

Edit :- Added runnable code and sample input and output to verify the correctness of program. Also Added the logic to print the index if element is found in the array and -1 index means element is not in array.

Input and output for number :- 120, which is not there in array.

Enter a number in the array: 
120
Element not found in array

for number 5 which is in array, output will be bbelow :-

Enter a number in the array: 
5
Element found at index : 1
Sign up to request clarification or add additional context in comments.

5 Comments

Try entering 5.
@KevinAnderson , found it adding the modifying code
Thank you for your feedback but for some reason when I put in a number that is not in the array it prints "...not in array" as well as "... found at index: -1" how do I fix that?
@michael , just add a condition to print it only if its not -1.
Thank you for the help @AmitK
2

You need to put the printline outside the loop:

public static int returnIndex(int[] haystack, int needle) {
        for (int n = 0; n < haystack.length; n++) {
            if (haystack[n] == needle) 
                return n;
        }

        System.out.println("Element not found in array");
        return -1;  
 }

Because if you get the element and return it with the return n; then the lower part won't be executed. Having it in the loop makes it print the not found text for every element that doesn't match the one you are looking for.

A better solution would be to print the element outside of the method, as follows:

public static int returnIndex(int[] haystack, int needle) {
     for (int n = 0; n < haystack.length; n++) {
        if (haystack[n] == needle) 
            return n;
     }
     return -1;  
}

public static void main(String[] args) {
     ...              
     int needle = sc.nextInt();
     if (returnIndex(haystack,needle) == -1){
           System.out.println("Element not found in array");
     }
     else {
           System.out.println("Element found in array");
     }
}

Comments

0

Try putting the System.out above the return -1, this way you won't print "Element not found in array" every time you don't find the number selected.

Comments

0

Try this

Just Make Small Change In returnIndex function it will work for you

public static int returnIndex(int[] haystack, int needle) {
    for (int n = 0; n < haystack.length; n++) {
        if (haystack[n] == needle) {
            return n;
        } else {
            if(n == haystack.length - 1)
            System.out.println("Element not found in array");
        }
    }
    return -1;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.