数组搜索:从数组中查找元素
1)查找元素是否存在
2)查找元素下标
public class Demo10 {
public static void main(String[] args) {
int[] arr = {43,56,74,5,46,45,78};
//查找元素是否存在
int target = 43;
boolean exists = false;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
//找到了
System.out.println("找到了");
System.out.println(i);//查找元素的下标
exists = true;
break;
}
}
if(!exists){
System.out.println("没有找到!");
}
}
}
3)查找元素的数量
public class Demo11 {
public static void main(String[] args) {
int[] arr = {43,56,74,5,46,45,78,78};
int target = 78;
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target){
count++;
}
}
System.out.println(count);
}
}