Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何获取元素的最后一个索引。(元素重复了几次)JAVA_Java_Arrays_Class_Indexing_Driver - Fatal编程技术网

如何获取元素的最后一个索引。(元素重复了几次)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);