get Index of last Element in list without using lastIndexOf() or any other Java/String- Methods [closed]

The below code works in getting the last index of a certain character:

public int lastIndex(char a, char[] data) {
    int max=-1;
    for(int i=0; i<data.length; i++) {
       if(data[i]==a) {
          max=i;
       }
    }
    return max;
}

It works by going through the array and finding the latest occurrence of a certain character. The variable ‘max’ is then set to this index. Once it goes through the whole array it will return ‘max’ if no character is found in the array it will just return ‘-1’ since that’s what ‘max’ was originally set to.

Browse More Popular Posts

Leave a Comment