使用java

时间:2015-04-23 07:28:37

标签: java arrays

我们正在尝试比较两个字符串数组(如[]和bs []),并使用bs []中的新字符串将数组字符串更新为[]。我们无法更新as [] .Pls帮助我们使用以下代码。谢谢你;)

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()); }

    }
}

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

看看Apache Commons ArrayUtils: 您可以使用包含和第三个临时数组的组合来存储差异(即!包含)。

感谢。

答案 2 :(得分:0)

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

这在Java中不起作用,正如Thilo在评论中所说的那样。一旦设置了大小,就无法增加数组的大小。

我建议使用ArrayList代替array。您可以简单地将新项添加到数组列表中而没有任何问题。

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