租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

java怎样在数组中查找指定元素,java怎么数组

发布时间:2024-05-08 17:41:56

java怎样在数组中查找指定元素

在Java中,可使用循环遍历数组来查找指定的元素。以下是一个简单的示例:

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.");
        }
    }
}

这段代码会在数组 arr 中查找元素 target,如果找到则输出找到的信息,如果没有找到则输出未找到的信息。