Java-数组的查询


package test;

import java.util.Iterator;

public class arr4 {
/*
 *数组的查询问题
 */
    public static void main(String[] args) {
        
        int arr[] = {11,23,55,66,88};
        //调用方法
        int index = getIndex(arr, 11);
        if (index!=-1) {
            System.out.println("此数的索引是"+index);
        }else {
            System.out.println("查无此数");
        }

    }
    /*
     定义一个方法:查询数组中指定的元素对应的索引:
     不确定因素:哪个数组,哪个指定元素(形参)
     返回值:索引
     */
    public static int getIndex(int arr[],int ele) {
        int index = -1;//这个初始值只要不是数组的索引即可
        for(int i=0;i<arr.length;i++) {
            if (arr[i]==ele) {
                index = i;//只要找到了元素,那么index就变成i
                break;//只要找到这个元素,循环就停止
            }
        }
        return index;
    }

}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM