溫馨提示×

java怎么判斷一個(gè)元素是否在數(shù)組中

小億
159
2024-01-30 16:43:02
欄目: 編程語言

在Java中,可以使用Arrays類中的binarySearch()方法或者自己寫一個(gè)循環(huán)來判斷一個(gè)元素是否在數(shù)組中。

使用binarySearch()方法需要先對(duì)數(shù)組進(jìn)行排序,然后調(diào)用該方法,它會(huì)返回要查找的元素在數(shù)組中的索引。如果返回的索引大于等于0,則表示該元素在數(shù)組中存在。否則,表示該元素不在數(shù)組中。

示例代碼如下所示:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        int target = 3;

        // 先對(duì)數(shù)組進(jìn)行排序
        Arrays.sort(arr);

        // 使用binarySearch()方法判斷元素是否存在
        int index = Arrays.binarySearch(arr, target);
        if (index >= 0){
            System.out.println(target + " 在數(shù)組中存在");
        } else {
            System.out.println(target + " 不在數(shù)組中存在");
        }
    }
}

另外,也可以自己寫一個(gè)循環(huán)來判斷元素是否在數(shù)組中。代碼如下所示:

public class Main {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        int target = 3;
        boolean exists = false;

        // 使用循環(huán)判斷元素是否存在
        for (int i : arr) {
            if (i == target) {
                exists = true;
                break;
            }
        }

        if (exists) {
            System.out.println(target + " 在數(shù)組中存在");
        } else {
            System.out.println(target + " 不在數(shù)組中存在");
        }
    }
}

0