java如何在數(shù)組中查找指定元素

小億
169
2024-05-08 17:41:56

在Java中,可以使用循環(huán)遍歷數(shù)組來(lái)查找指定的元素。以下是一個(gè)簡(jiǎn)單的示例:

public class Main {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        int target = 3;
        
        boolean found = false;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == target) {
                found = true;
                break;
            }
        }
        
        if (found) {
            System.out.println("Element " + target + " found in the array.");
        } else {
            System.out.println("Element " + target + " not found in the array.");
        }
    }
}

這段代碼會(huì)在數(shù)組 arr 中查找元素 target,如果找到則輸出找到的信息,如果沒(méi)有找到則輸出未找到的信息。

0