Java 程式來列印給定 Java 整數陣列的所有不同元素
列印陣列的所有不同元素,即陣列中的所有元素僅列印一次,不列印重複元素。下面給出了一個示例。
Array = 1 5 9 1 4 9 6 5 9 7 Distinct elements of above array = 1 5 9 4 6 7
演示此問題的程式如下。
示例
public class Example {
public static void main (String[] args) {
int arr[] = {1, 5, 9, 1, 4, 9, 6, 5, 9, 7};
int n = arr.length;
int i, j;
System.out.print("The array is: ");
for (i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
System.out.print("
The distinct elements of above array are: ");
for (i = 0; i < n; i++) {
for (j = 0; j < i; j++)
if (arr[i] == arr[j])
break;
if (i == j)
System.out.print( arr[i] + " ");
}
}
}輸出
The array is: 1 5 9 1 4 9 6 5 9 7 The distinct elements of above array are: 1 5 9 4 6 7
現在讓我們瞭解一下上述程式。
首先顯示原始陣列。此陣列可能包含重複的元素。演示此過程的程式碼片段如下所示 -
System.out.print("The array is: ");
for (i = 0; i < n; ++i)
System.out.print(arr[i] + " ");現在,使用一個巢狀 for 迴圈來確保只顯示陣列的不同元素。外迴圈從 0 執行到 n,內迴圈確保只在元素以前未發生時才打印該元素。演示此過程的程式碼片段如下所示 -
System.out.print("
The distinct elements of above array are: ");
for (i = 0; i < n; i++) {
for (j = 0; j < i; j++)
if (arr[i] == arr[j])
break;
if (i == j)
System.out.print( arr[i] + " ");
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP