如何从Java中的数组中提取不同的值?
要提取数组中的不同值,您需要将数组中的每个元素与其余所有元素进行比较,如果匹配,则得到重复的元素。为此,一种解决方案是您需要使用两个循环(嵌套),其中内部循环以i+1开头(其中i是外部循环的变量),以避免重复。
示例
import java.util.Arrays;
import java.util.Scanner;
public class DetectDuplcate {
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("The array created is ::"+Arrays.toString(myArray));
System.out.println("indices of the duplicate elements :: ");
for(int i=0; i<myArray.length; i++) {
for (int j=i+1; j<myArray.length; j++) {
if(myArray[i] == myArray[j]) {
System.out.println(j);
}
}
}
}
}输出结果
Enter the size of the array that is to be created :: 6 Enter the elements of the array :: 87 52 87 63 41 63 The array created is :: [87, 52, 87, 63, 41, 63] indices of the duplicate elements :: 2 5
热门推荐
10 朋友新年祝福语大全 简短
11 新年祝福语简短大方兔年
12 搬新家礼物祝福语简短
13 同学见面花束祝福语简短
14 五一假期祝福语幽默简短
15 离职欢送敬酒祝福语简短
16 对学弟的祝福语简短
17 考老师辞职祝福语简短
18 祝福语驱散霉运的话简短