可以使用循环遍历数组,逐个比较数组中的元素是否与目标元素相等,如果有相等的元素,则认为数组包含该元素。
以下是一个示例代码:
public class Main { public static void main(String[] args) { int[] array = {1, 2, 3, 4, 5}; int target = 3; boolean contains = false; for (int i = 0; i < array.length; i++) { if (array[i] == target) { contains = true; break; } } if (contains) { System.out.println("数组包含目标元素"); } else { System.out.println("数组不包含目标元素"); } } }
这里定义了一个名为contains
的布尔变量,初始值为false
。在循环遍历数组时,如果发现有元素与目标元素相等,则将contains
变量设为true
,并使用break
语句跳出循环。最后根据contains
变量的值输出判断结果。