Search code examples
javaarrayslinear-search

Find if a number is in an array, and if so, how many times does it appear


The problem is there is an array of 10000 that is already filled for me. The range of numbers that will fill the array will be between 0 and 2500. The array is unsorted. My goal is to find the existence of 1320 through one linear search, and the second linear search will check how many times the number 1320 appears. The array is a random array.

I have tried setting up a linear search that will check whether the number in the array exists. I have also tried to set up the linear search that will check how many times an array exists. Neither worked, this is my first time working with arrays so I am not sure if I am even doing them correctly

public static void main(String[] args) {
    // Finish adding Code
    boolean DoesItExist;
    int iHowMany;
    final int SIZE = 10000, ENTRY = 1320;
    int[] NumArray = new int[SIZE];


    OwenHeading.getHeader("Assignment 9: Arrays.");
    fillTheArray(NumArray, SIZE);
    System.out.println("DONE");
}


public static void fillTheArray(int[] iTempArray, int SIZE) {
    final int RANGE = 2500;
    Random rand = new Random();

    for (int index = 0; index <= SIZE - 1; index++)
        iTempArray[index] = rand.nextInt(RANGE);
}

public static boolean linearSearchOne(int[] iTempArray, int SIZE, int ENTRY) {

    boolean TempDoesItExist;

    return TempDoesItExist;
}

public static int linearSearchTwo(int[] iTempArray, int SIZE, int ENTRY) {

    int HowManyExist;

    return HowManyExist;
}

public static void programOutput(boolean TempDoesItExist, int TempHowMany) {

    if (TempDoesItExist)
        System.out.println("does");
        // Cool, you found the number 1320
    else
        System.out.println("does not");
        // Dang, you didn't find the number 1320
}

}

I am not asking for the exact answer, just some help that will get me going into the right direction. I feel like I would be able to do this project easier if I started from scratch, but my teacher wants us to use his starter project.


Solution

  • you can modify two methods of linear search you have in this way and that is going to work : just declare a counter and increment it each time you find your ENTRY number.

    public static boolean linearSearchOne(int[] iTempArray, int SIZE, int ENTRY) {
        for (int i = 0; i < SIZE; i++) {
            if (iTempArray[i] == ENTRY) {
                return true;
            }
        }
        return false
    }
    
    public static int linearSearchTwo(int[] iTempArray, int SIZE, int ENTRY) {
    
        int HowManyExist;
        for (int i = 0; i < SIZE; i++) {
            if (iTempArray[i] == ENTRY) {
                HowManyExist ++;
            }
        }
        return HowManyExist;
    }