溫馨提示×

java 數組中是否存在某個值

小億
118
2024-01-10 15:54:45
欄目: 編程語言

在Java中,可以使用循環遍歷數組來判斷數組中是否存在某個值。下面是一個示例代碼:

public class Main {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5};
        int target = 3;
        boolean found = false;
        
        for (int i = 0; i < array.length; i++) {
            if (array[i] == target) {
                found = true;
                break;
            }
        }
        
        if (found) {
            System.out.println("數組中存在目標值" + target);
        } else {
            System.out.println("數組中不存在目標值" + target);
        }
    }
}

輸出:

數組中存在目標值3

在上面的代碼中,我們使用了一個布爾變量found來標記是否找到了目標值。在遍歷數組的過程中,如果找到了目標值,將found設置為true并跳出循環。最后根據found的值來判斷是否存在目標值。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女