数组元素查找(查找指定元素第一次在数组中出现的索引)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Cheng_May/article/details/81087072

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
            }
        
       

猜你喜欢

转载自blog.csdn.net/Cheng_May/article/details/81087072