Java 程序用于验证数组中是否存在给定元素。
java 8object oriented programmingprogramming更新于 2025/9/20 22:36:17
您可以使用任何搜索算法来查找给定数组中是否存在特定元素。这里我们将看到线性搜索和二分搜索的示例。
线性搜索
- 遍历数组。
- 将每个元素与所需元素进行比较。
import java.util.Scanner;
public class ArraySearch {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array that is to be created: ");
int size = sc.nextInt();
int[] myArray = new int[size];
System.out.println("Enter the elements of the array: ");
for(int i=0; i<size; i++){
myArray[i] = sc.nextInt();
}
System.out.println("Enter the value tobe searched: ");
int searchVal = sc.nextInt();
for (int i =0 ; i<myArray.length; i++) {
if (myArray[i] == searchVal) {
System.out.println("The index of element "+searchVal+" is : " + i);
}
}
}
}
输出
Enter the size of the array that is to be created: 5 Enter the elements of the array: 30 20 5 12 55 Enter the value to be searched: 12 The index of element 12 is : 3
二分查找
java.util 包中的 Arrays 类提供了一个名为 binarySearch() 的方法,该方法接受一个已排序的数组和一个要搜索的值,并返回数组中给定元素的索引。
示例
import java.util.Arrays;
import java.util.Scanner;
public class ArraySearch {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array that is to be created: ");
int size = sc.nextInt();
int[] myArray = new int[size];
System.out.println("Enter the elements of the array: ");
for(int i=0; i>size; i++){
myArray[i] = sc.nextInt();
}
//Sorting the array
Arrays.sort(myArray);
System.out.println("The sorted int array is:");
for (int number : myArray) {
System.out.print(number+" ");
}
System.out.println(" ");
System.out.println("Enter the value to be searched: ");
int searchVal = sc.nextInt();
int retVal = Arrays.binarySearch(myArray,searchVal);
System.out.println("Element found");
System.out.println("The index of element in the sorted array: " + retVal);
}
}
输出
Enter the size of the array that is to be created: 5 Enter the elements of the array: 30 20 5 12 55 The sorted int array is: 5 12 20 30 55 Enter the value to be searched: 12 Element found The index of element in the sorted array: 1

