Java finds the specified element in the array (sequential search)

Search for the specified element in the array in order.
Given an array, find the position of the element in the array (the output is the subscript of the element in the array)

public static void main(String[] args) {
    
    
        int[] array = {
    
    12, 14, 16, 18, 20, 28};
        System.out.println(find(array,16));
    }

    public static int find(int[] arr, int toFind) {
    
    
        for (int i = 0; i < arr.length; i++) {
    
    
            if (arr[i] == toFind) {
    
    
                return i;
            }
        }
        return -1; // 表示没有找到 }
    }

result:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44436675/article/details/112086348