如何在 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

更新於:30-Jul-2019

930 閱覽

開啟你的職業生涯

完成該課程以獲得認證

開始
廣告
© . All rights reserved.