2012-12-20 125 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