2015-04-23 24 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,您可以創建一個更長的新陣列並在此處複製舊陣列並添加新元素。我不會推薦這個。