This question already has answers here:
How to find the index of an element in an array in Java?
(14个回答)
3年前关闭。
我有这个类,它在首选输入后显示数组的值:
该程序显示以下输出:
2 3 4 5 6
现在我想找到4的索引,使之等于2,但是如何将其放入程序中呢?
(14个回答)
3年前关闭。
我有这个类,它在首选输入后显示数组的值:
class MyArrayList {
private int [] myArray;
private int size;
public MyArrayList (int value, int seed, int inc){
myArray = new int [value];
size = value;
for (int i = 0; i < size; i++) {
myArray [i] = seed;
seed += inc;
}
}
}
public class JavaApp1 {
public static void main(String[] args) {
MyArrayList a = new MyArrayList(5, 2, 1);
a.printList();
}
}
该程序显示以下输出:
2 3 4 5 6
现在我想找到4的索引,使之等于2,但是如何将其放入程序中呢?
最佳答案
循环获取值,然后有了索引,您可能希望将此作为MyArrayList类的函数
int[] myArray = {2,3,4,5,6};
for (int i = 0; i < myArray.length; i++)
{
if( myArray[i] == 4 )
System.out.println( "index=" + i);
}