查找数组中的最后一个零索引

use*_*435 1 java

我编写了以下代码来查找数组中的最后一个零索引:

public class Stack {
    public static void main(String[] args){
        int[] a=new int[5];
        a[0]=1;
        a[1]=0;
        a[2]=90;
        a[3]=0;
        a[4]=4;
        findLast(a);
    }
    public static int findLast(int[] x){
        for(int i=0;i<x.length;i++){
         if(x[i]==0){
             System.out.println(i);             
         }
        }
        return 0;
    }
}
Run Code Online (Sandbox Code Playgroud)

输出如下:

1
3
Run Code Online (Sandbox Code Playgroud)

我真正想要的是指数3.

das*_*ght 6

  • 从数组的末尾开始(即i=x.length-1)
  • 递减i而不是递增(即使用i--)
  • 一旦达到零就停止(即添加break之后println).
  • 设置停止条件,使循环处理索引为零的元素.