sup
sup

Reputation: 31

how to get the last index of element. (element is repeated a few times) JAVA

I'm using this in my driver a.indexFinder(4) and also a.indexFinder(2) if the element is not in the array then we are to return a -1

This code work when the index is 5(i get a -1) because 5 is not in the array. but for 4 it is giving me the index for the first 4.i want the last 4.

int[] array = {2, 8, 8, 3, 4, 4, 4, 7}; //im suppose to find the index of the last 4.
int index = 4; //4 or 5(return -1 when element is not found)
public int findLast(int index) //this method is in my class
{         
    for(int index = 0; index < a.length; index++)
    {
    if (a[index]== key)
    return index;
    }
     return -1;
}

Upvotes: 0

Views: 86

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347204

One possible approach would be to start at the end of the array and work your way backwards, returning the index of the first element you encounter....

int[] array = new int[]{2, 8, 8, 3, 4, 4, 4, 7}; //im suppose to find the index of the last 4.
int find = 4; //4 or 5(return -1 when element is not found)

int lastIndex = -1;
for (int index = array.length - 1; index >= 0; index--) {
    if (array[index] == find) {
        lastIndex = index;
        break;
    }
}

System.out.println(lastIndex);

Upvotes: 1

Suresh Sajja
Suresh Sajja

Reputation: 562

traverse from last index (a.length - 1) to 0

return the index when you first encountered the key.

Upvotes: 3

Related Questions