数组中(包含10个元素,每个元素的值在[15,20]之间)
* 求某个元素首次出现的索引、
* 最后一次出现的索引、
* 所有对应的索引位置
/*
1.数组中(包含10个元素,每个元素的值在[15,20]之间)
* 求某个元素首次出现的索引、
* 最后一次出现的索引、
* 所有对应的索引位置*/
Random random=new Random();
int[] array=new int[10];
for(int i=0;i<array.length;i++) {
array[i]=random.nextInt(6)+15;
}
//首次出现的索引
int firstIndex=-1;
for(int i=0;i<array.length;i++) {
System.out.print(array[i]+" ");
if(array[i]==18) {
firstIndex=i;
break;
}
}
System.out.println();
if(firstIndex==-1) {
System.out.println("数组中没有要找的元素");
}else {
System.out.println(firstIndex);
}
//最后一次出现的索引
int lastIndex=-1;
for(int i=0;i<array.length;i++) {
System.out.print(array[i]+" ");
if(array[i]==18) {
lastIndex=i;
}
}
System.out.println();
if(lastIndex==-1) {
System.out.println("数组中没有要找的元素");
}else {
System.out.println(lastIndex);
}
//所有对应的索引位置
for(int i=0;i<array.length;i++) {
System.out.print(array[i]+" ");
if(array[i]==18) {
System.out.print("("+i+")");
}
}
System.out.println();
if(lastIndex==-1) {
System.out.println("数组中没有要找的元素");
}
18
0
18 19 16 18 16 17 17 16 15 19
3
18 (0)19 16 18 (3)16 17 17 16 15 19