2012-12-20 124 views
0

我想比較兩個陣列和存儲在另一個陣列的差比較兩個陣列串的和結果存儲在另一個陣列

例如兩個陣列可能是

String[] a1 = { "cat" , "dog" }; 
String[] a2 = { "cat" , "rabbit" }; 

所得陣列將像這樣

{ "rabbit" } 

我用這個代碼,但它不工作

int n = 0; 
for (int k = 0; k <= temp.length; k++) 
{ 
    for (int u = 0; u <= origenal.length; u++) 
    { 
     if (temp[k] != origenal[u] && origenal[u] != temp[k]) 
     { 
      temp2[n] = temp[k]; 
      System.out.println(temp[u]); 
      n++; 
     } 
    } 
} 
+7

[什麼您是否嘗試過?](http://mattgemmell.com/2008/12/08/what-have-you-tried/) –

+4

簡單:'String result =「rabbit」;' – Maroun

+0

更具體。 – HericDenis

回答

1

這應該可以做到。

String[] result = new String[100]; 
Int k = 0; 
Boolean test = true; 
for(i=0; i < a1.length; i++){ 
    for(j=0; j < a2.length; j++){ 
     if(a2[i].equals(a1[i])) continue; 
     test = false 
    } 
    if(test == false) result[k++] = a1[i]; 
} 
+0

你知道這會給他完全錯誤的答案嗎? – user902383

+0

@ user902383杜,是的,發現它剛剛發佈後 –

+0

編輯&修復。 –

1

我認爲這可能是你在找什麼。請注意,如果該值存在於第二個數組中,但不在第一個數組中,它將僅添加到第三個「數組」中。在你的例子中,只有兔子會被儲存,而不是狗(儘管兩條狗都不存在)。這個例子可能會縮短,但我想保持這樣,所以更容易看到發生了什麼。

首次進口:

import java.util.ArrayList; 
import java.util.List; 

然後執行以下操作來填充和分析陣列

String a1[] = new String[]{"cat" , "dog"}; // Initialize array1 
String a2[] = new String[]{"cat" , "rabbit"}; // Initialize array2 

List<String> tempList = new ArrayList<String>(); 
for(int i = 0; i < a2.length; i++) 
{ 
    boolean foundString = false; // To be able to track if the string was found in both arrays 
    for(int j = 0; j < a1.length; j++) 
    { 
     if(a1[j].equals(a2[i])) 
     { 
      foundString = true; 
      break; // If it exist in both arrays there is no need to look further 
     } 
    } 
    if(!foundString) // If the same is not found in both.. 
     tempList.add(a2[i]); // .. add to temporary list 
} 

tempList現在將包含「兔」爲根據的規範。如果有必要需要它是第三個數組,你可以很簡單地做它轉換成如下:

String a3[] = tempList.toArray(new String[0]); // a3 will now contain rabbit 

要打印在清單或陣列的內容做:

// Print the content of List tempList 
for(int i = 0; i < tempList.size(); i++) 
{ 
    System.out.println(tempList.get(i)); 
} 

// Print the content of Array a3 
for(int i = 0; i < a3.length; i++) 
{ 
    System.out.println(a3[i]); 
} 
+0

在此語句中存在錯誤(String s2:a2),錯誤是「預計的」;是否存在任何導入? – user1888020

+0

您應該只需要java.util.ArrayList並導入java.util.List以使用該列表。我可以重建循環以不使用for-each變體。 – MrKiane

+0

@ user1888020你可以從'for(String s2:a2)'改變爲'for(int i = 0; i HericDenis