I have to write a method called LastIndexOf that accepts an integer value as a parameter and that returns the index in the list of the last occurrence of the value, or -1 if the value is not found. This is the code I have but it doesn’t return anything. To me it looks that it always is going to return -1 but I can’t see it on the output because it doesn’t print what the method returns.
these are the values that list stores.
list -> [2, 5, 7, 24, 5, 9, 13, 2]
public class LastIndexOf {
public static void main(String[] args) {
System.out.println("index of 5 = " + list.lastIndexOf(5)); // should to return index of 5= 4
System.out.println("index of 100 = " + list.lastIndexOf(100)); // should return index of 100 = -1
}
public static int lastIndexOf (int element) {
int index = 0;
ListNode current = list;
while (current != null) {
if (current.data == element) {
return index;
}
index ++;
current = current.next;
}
return -1;
}
}
This is the output I get:
index of 5 =
index of 100 =