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