Skip to content

Eliminating a search element in an array

The java program prompts the user to input a number to search for and prints a message: “Found [search key]” if the number exists in the array elements, then print the remaining data on the next line eliminating the searched element. Otherwise, it prints: “Not found [search key]”. This is what I have so far

import java.util.Scanner;

public class lbArrayActOne_Cruz {

    public static void main (String[]args) {
    
        int [] arr;
        arr = new int [] {1, 45, 23, 46, 78, 8, 9, 0, 67, 69, 12, 100, 84, 72, 420};
        int nItems = 0;
        int j;
        int searchId;
        nItems = 15;
    
        Scanner input = new Scanner (System.in);
    
        for (j=0; j<nItems; j++)
            System.out.print(arr[j]+ " ");

        System.out.println(" ");
    
        System.out.print("Enter a Number: ");
        searchId = input.nextInt();
    
        for (j=0; j<nItems; j++)
            if (arr[j] == searchId)
                break;

        if (j==nItems)
            System.out.println("Can't Find " + searchId);
        else
            System.out.println("Found " + searchId);
    }
}

Answer

You have almost done it. What is missing is:

  • You need to store the “found” result in some boolean variable, so that you know later whether to print out the rest of the data. I would recommend doing it this way instead of the check j==nItems. You seem to be using j for several loops and this is error-prone.
  • You need to print out the rest of the data, if the searched for value was found.

Here is the modified code, with additions marked by comments:

import java.util.Scanner;

public class lbArrayActOne_Cruz {

    public static void main (String[]args) {
    
        int [] arr;
        arr = new int [] {1, 45, 23, 46, 78, 8, 9, 0, 67, 69, 12, 100, 84, 72, 420};
        int nItems = 0;
        int j;
        int searchId;
        nItems = 15;
        
        Scanner input = new Scanner (System.in);
        
        for (j=0; j<nItems; j++)
            System.out.print(arr[j]+ " ");
        
        System.out.println(" ");
    
        System.out.print("Enter a Number: ");
        searchId = input.nextInt();
        
        // This variable will store whether the value was found
        boolean found = false;
        for (j=0; j<nItems; j++)
            if (arr[j] == searchId) {
                // Found
                found = true;
                break;
            }
        
        // Using the variabl "found" for a more readable check
        if (!found)
            System.out.println("Can't Find " + searchId);
        else {
            System.out.println("Found " + searchId);
            
            // Now print out the array, skipping the value
            for (j=0; j<nItems; j++) {
                if (arr[j] != searchId) {
                    System.out.print(arr[j]+ " ");
                }
            }
        }
    }
}