2015-04-23 61 views
-6

我们试图比较两个字符串数组(作为[]和bs [])并使用bs []中存在的新字符串将数组字符串更新为[]。我们无法更新在为[] .PLS帮助我们提供以下codes.Thank U;)使用java比较两个字符串数组

public class Aa { 

/** 
* @param args the command line arguments 
*/ 
public static void main(String[] args) { 


    // Create an array of 4 strings (indexes 0 - 3) 

    String as[] = new String[5]; 
    String bs[] = new String[16]; 
    int i; 



    try { 

     // Create a bufferreader object to read our file with. 

     BufferedReader reader = new BufferedReader(new FileReader("input.txt")); 
     BufferedReader reader1; 
     reader1 = new BufferedReader(new FileReader("a1.txt")); 


     // Line will hold our line read from the file 
     String line = ""; 
     String line1 = ""; 


     // The counter will keep track of how many lines we have read 

     int counter = 0; 
     int counter1 = 0; 


     // Read in a line from the file and store it in "line". Do this while we don't hit null or while the counter is less than 4. 

     // The counter prevents us from reading in too many lines. 

     while (((line = reader.readLine()) != null) && (counter < 4)) { 

      as[counter] = line; 

      counter++; 

     } 

     while (((line1 = reader1.readLine()) != null) && (counter1 < 16)) { 

      bs[counter1] = line1; 

      counter1++; 

     } 

     System.out.println("value"+as[0]); 
      System.out.println("value"+bs[0]); 
     int temp,temp1,j; 
     temp=as.length; 
     temp1=bs.length; 
     System.out.println("length:"+temp); 
     System.out.println("length1:"+temp1); 
     for(i=0;i<bs.length;i++) 
     { 
      for(j=0;j<as.length;j++) 
      { 
       if(as[j].equals(bs[i])) 
       { 
        //ignore 
       } 
       else 
       { 
        temp++; 
        as[temp]=bs[i]; 

       } 
      } 

     } 


     // With a foreach style loop we loop through the array of strings and print them out to show they were read in. 



     reader1.close(); 
     reader.close(); 

    } 

    catch (Exception ex) { System.out.println("Exception: " + ex.getMessage()); } 

    } 
} 
+2

您不清楚,它是什么意思'用bs []' – amit

+1

中的新字符串将数组字符串更新为[]。如果您尝试追加到数组中,那么在Java中不起作用。数组是固定长度的。 – Thilo

+0

'//创建4个字符串的数组(索引0-3)':不要忘记更新您的评论 –

回答

0

看看阿帕奇百科全书ArrayUtils: 您可以使用组合含有和第三临时数组存储差异(即!包含)。

谢谢。

1

由于您使用的两个阵列只包含字符串,它能够更好地都转换为列出并添加

List aList = (Arrays.asList(as)); 
List bList = (Arrays.asList(bs)); 
bList.removeAll(aList); // assuming you have some common objects in both 
aList.addAll(bList); 
as = aList.toArray(); // Convert back to array 
+0

我得到“不支持的操作异常” –

+0

请您分享您的代码以及异常 –

+0

bList.removeAll一个列表); aList.addAll(bList); as =(String [])aList.toArray(as); (aList a:list){ System.out.println(a); }我得到不支持的操作exception.How打印arraylist的内容? –

0
else 
{ 
    temp++; 
    as[temp]=bs[i]; 
} 

这并不在Java中工作作为蒂洛在评论中说。一旦设置了大小,您就不能增加数组的大小。我建议使用ArrayList而不是array。您可以简单地将新项目添加到数组列表中,而不会有任何问题。

如果您坚持使用arrays,您可以创建一个更长的新阵列并在此处复制旧阵列并添加新元素。我不会推荐这个。