我编写了以下代码来查找数组中的最后一个零索引:
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;
}
}
输出如下:
1
3
我真正想要的是索引 3。
最佳答案
- 从数组末尾开始(即
i=x.length-1
) - 递减
i
而不是递增(即使用i--
) - 一达到零就停止(即在
println
之后添加break
)。 - 设置停止条件,使循环处理索引为零的元素。
关于java - 查找数组中最后一个零的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14657278/