Home > Blockchain >  Method that takes an int array and a value and returns the index of that value in the array
Method that takes an int array and a value and returns the index of that value in the array

Time:03-23

I've spent like an hour trying to figure this one out and I couldn't. This is an exercise for a Java elective course I am taking and I could use some help.

Write a method linearSearch() that takes an array of integers, and an integer value. It should then return the index of the value inside the array (by using a for loop to traverse the elements one by one in order). If the value is not found, -1 should be returned. If more than one value is found, the first occurrence should be returned. Write a program to test your method.

So this is what I tried doing.

public class Exercise6 {
    public static void main(String [] args) {
        int[] a = {3, 6, 70, 3, 7, 9};
        linearSearch(a, 3);
        
    }

    public static void linearSearch(int[] a, int n){  
        int index;      

        for (int i = 0; i < a.length; i  ){
            if (a[i] == n){
                index = i;
                break;
            }
            else {
                index = -1;
            }
        }
        System.out.print(index);
    }
}

But this is obviously wrong. Could you please point me in the right direction? I don't necessarily want you to give me the answer, just give me an idea about the steps.

CodePudding user response:

This will through compilation error as int index; is not initialized. Once initialized, else part would become redundant. Rest would work and deliver you the expected output.

CodePudding user response:

The problem is that you didn't initialize the variable (index):

int index = -1;

but you should think at another way as follows:

1 - read what you want to do

2- You need to make a function that return the index of a specific value of array

3- Define the return type of the function ==> you need to return the index then the function return type is int

4- Define the parameters ==> you have 2 parameters : array and the value

5- You should return the index of value or -1 if it doesn't exist then you will initialize the index = -1

6- Code will be as follows:

public class Exercise6
{
    public static int linearSearch(int[] a, int n){  
        int index = -1;      

        for (int i = 0; i < a.length; i  ){
            if (a[i] == n){
                index = i;
                break;
            }
        }
        return index;
    }

    public static void main(String[] args) {
        int[] a = {3, 6, 70, 3, 7, 9};
        System.out.println(linearSearch(a, 7));
    }
}

Think before Coding

All the best

  • Related