`
zjp1991326
  • 浏览: 1127 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
最近访客 更多访客>>
社区版块
存档分类
最新评论

我有两个数组, 想拿出两个数组中不同的数字

阅读更多
我有两个数组,{1,3,2,5,6,8},{7,4,9,1,5}
想取出这两个数组中不同的数字,
                
                String []s1=  { "1","3","2","5","6","8"};
                 String []s2=  {"7","4","9","1","5"};
                 for(int i=0;i<s1.length;i++){
                         for (int j = 0; j < s2.length; j++) {
                                 if(s1[i] != s2[j]){
                                         System.out.println(s1[i]);
                                 }
                         }
                 }

        上面是我写的,    运行后显示不一样的数字每个都显示了5遍,    能不能只显示一遍?
分享到:
评论
1 楼 412195581 2012-01-14  
String []s1=  { "1","3","2","5","6","8"};
String []s2=  {"7","4","9","1","5"};
List<String> sameList = new ArrayList<String>();//2数组相同的元素集合
for(int i=0;i<s1.length;i++){
    boolean flag = false;
    for(int j=0;j<s2.length;j++){
        if(s1[i].equals(s2[j]){
            flag = true;
            sameList.add(s1[i]);
            break;
        }
    }
    if(!flag){
         System.out.println(s1[i]);
    }
}
for(int i=0;i<s2.length;i++){
     boolean flag = false;
     for(int j=0;j<sameList.size();j++){
        if(s2.length.equles(sameList.get(j))){
             flag = true;
             break;
        }
     }
     if(!flag){
        System.out.println(s2[i]);
     }
}

相关推荐

Global site tag (gtag.js) - Google Analytics