2014-09-28 81 views
-2

我已經接受了涉及兩個數組的練習。例如:陣列中的單個元素

String [] array1 = { "Tv","Iphone","Pc" }; 
String [] array2 ={"Tv" , "Pc"} 

(在現實中,這些陣列可以容納幾百元從文件中來。)

  1. 我需要找到的所有元素/元素?在第二個數組中存在/不存在的第一個數組的第一個數組。我正在考慮使用for循環或StringTokenizer。我只需要使用數組來解決這個練習。

  2. 如何添加一些原始int第二個數組來表示我錯過了這些數據。

+2

請加上這是指(Java的?)作爲標記語言。 – 2014-09-28 21:10:12

+0

對不起。我只是添加它。爲您的建議thnks。 – 2014-09-28 21:12:21

+0

我還不確定你的問題是什麼。你想用數組做什麼? – 2014-09-28 21:13:20

回答

0
// Variables 
String [] array1 = {"a", "b", "c", "d"}; 
String [] array2 = {"a", "c", "e"}; 
String [] distinct = new String[array1.length]; 
int i, j, k = 0; 
boolean match; 

// Search 
for (i = 0; i < array1.length; i++) { 
    match = false; 
    for (j = 0; j < array2.length; j++) { 
     if (array1[i].equals(array2[j])) { match = true; break; } 
    } 
    if (!match) { distinct[k] = array1[i]; k++; } 
} 

// Output 
for (i = 0; i < k; i++) { 
    System.out.println(distinct[i]); // b, d 
} 
+0

thriks很多Jose – 2014-09-28 21:45:53

0

鑑於這兩個數組作爲一個例子:

String[] arr1 = new String[] {"A", "B", "C", "D", "E"}; 
    String[] arr2 = new String[] {"A", "C", "D"}; 

好,只用數組,我會做這樣的事情:

首先,一個方法,看看一個數組包含一些值:

public boolean aContainsB(String[] a, String b) { 
    for (String s : a) if (s.equals(b)) return true; 
    return false; 
} 

然後,創建一個與最大數組一樣大的新數組。它將保存不在數組中的值。它可能是每個字母,我假設。

String[] notFound = new String[Math.max(arr1.length, arr2.length)]; 

然後,循環遍歷第一個數組,如果當前值不在第二個數組中,則將其追加到未找到的數組。

int i = 0; 
    for (String s : arr1) if (!aContainsB(arr2, s)) notFound[i++] = s; 

在本月底,我會包含多少值不存在第二陣列中,你可以通過NOTFOUND陣列循環我次打印出來。

System.out.println("There are " + i + " elements in arr1 that are not in arr2, they are:"); 
    for (int j = 0; j < i; j++) { 
     System.out.println("The String: " + notFound[j]); 
    } 

輸出將是:

There are 2 elements in arr1 that are not in arr2, they are: 
The String: B 
The String: E 
+0

thnks爲您的答覆男人。我非常感謝你的例子。 此致敬意 – 2014-09-28 21:45:14