public static void main(String[] args) {
/*String [] ac = {"sche"," ","1123","we"};
String a = "we";
for(int i=0;i< ac.length;i++){
if(ac[i]==a){
System.out.println("索引位置是:"+i);
break;
}
}*/
/*
* 查找数组中指定元素第一次出现的索引值。
int[] arr = {98,23,16,35,72};
查找23在数组中的索引值。
*/
System.out.println(getIndex(23));
}
private static int getIndex(int x) {
int[] arr = {98,23,16,35,72};
for (int i = 0; i < arr.length; i++) {
if (arr[i] == x) {
return i;
}
}
return -1; //若数组中没有则返回-1
}
数组元素查找(查找指定元素第一次在数组中出现的索引)
最新推荐文章于 2025-10-23 00:05:39 发布
本文介绍了一种在Java中查找指定元素在数组中首次出现的索引位置的方法。通过遍历整型数组并使用if条件判断,实现了对指定数值的搜索,并返回其位置。如果数组中不存在该元素,则返回-1。
525

被折叠的 条评论
为什么被折叠?



