如何获取元素的最后一个索引。(元素重复了几次)JAVA
我在我的驱动程序如何获取元素的最后一个索引。(元素重复了几次)JAVA,java,arrays,class,indexing,driver,Java,Arrays,Class,Indexing,Driver,我在我的驱动程序a.indexFinder(4)和a.indexFinder(2) 如果元素不在数组中,则返回-1 这段代码在索引为5时工作(我得到了-1),因为数组中没有5。 但是对于4,它给了我前4个的索引。我想要最后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
a.indexFinder(4)
和a.indexFinder(2)
如果元素不在数组中,则返回-1
这段代码在索引为5时工作(我得到了-1),因为数组中没有5。
但是对于4,它给了我前4个的索引。我想要最后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;
}
int[]数组={2,8,8,3,4,4,4,7}//我想找到最后4个的索引。
int指数=4//4或5(未找到元素时返回-1)
public int findLast(int index)//此方法在我的类中
{
for(int index=0;index
从最后一个索引(a.length-1)遍历到0
当您第一次遇到该键时返回索引。从上一个索引(a.length-1)遍历到0
当您第一次遇到该键时返回索引。一种可能的方法是从数组的末尾开始,然后向后操作,返回遇到的第一个元素的索引
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);
一种可能的方法是从数组的末尾开始,然后向后操作,返回遇到的第一个元素的索引
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);