我必须编写一个名为 LastIndexOf 的方法,该方法接受一个整数值作为参数,并返回该值最后一次出现的列表中的索引,如果未找到该值,则返回 -1。这是我拥有的代码,但它不返回任何内容。对我来说,它看起来总是会返回 -1 但我在输出中看不到它,因为它不打印该方法返回的内容。
这些是列出商店的值。
列表 -> [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;
}
}
这是我得到的输出:
index of 5 =
index of 100 =