解决难题,数组编程,java

时间:2014-02-06 10:23:55

标签: java arrays

我有一个问题:我无法检查两个阵列A和B中的元素是否相同...为什么这不起作用? 问题在于我的程序的这一部分,并且在if(A.get(j)== B.get(i))中,有一些我不知道的数组。

     for(int i=0; i<n; i++){
          if(B.get(i) != A.get(i)){
              for(int j=0; j<n; j++){
                  if(A.get(j)==B.get(i)){
                      Collections.swap(B, j, i);
                      System.out.println("Swapping "+i+" with "+j+" : "+B);
                      count++;
                  }
              }
          }
      }

洞程序是......       import java.util.ArrayList;       import java.util.Collections;       import java.util.Scanner;

  public class Opgave4Uge6 {
      private static Scanner s;

      public static void main(String arg[]){

      int n = s.nextInt();

      long time = System.currentTimeMillis();

      ArrayList<Integer> A = new ArrayList<>(); 
      for(int a=0; a<n ;a++){
          A.add(new Integer(a));
      }
      System.out.println("The solution");
      System.out.println(A);

      ArrayList<Integer> B = new ArrayList<>(); 
      for(int b=0; b<n ;b++){
          B.add(new Integer(b));
      }
      Collections.shuffle(B);

      System.out.println("The random list");
      System.out.println(B);

      int count = 0;

      for(int i=0; i<n; i++){
          if(B.get(i) != A.get(i)){
              for(int j=0; j<n; j++){
                  if(A.get(j)==B.get(i)){
                      Collections.swap(B, j, i);
                      System.out.println("Swapping "+i+" with "+j+" : "+B);
                      count++;
                  }
              }
          }
      }
      System.out.println(B+" Solved!");
      System.out.println("Number of moves "+count);
      int k = n-count;
      System.out.println("Number of cycles "+k);
      long newtime = System.currentTimeMillis()-time;
      System.out.println("Time "+newtime+" ms");
      }
  }

BTW:我正在使用Netbeans。

1 个答案:

答案 0 :(得分:2)

它不是关于arrays.use .equals()方法

for(int i=0; i<n; i++){
          if(!B.get(i).equals(A.get(i))){
              for(int j=0; j<n; j++){
                  if(A.get(j).equals(B.get(i))){
                      Collections.swap(B, j, i);
                      System.out.println("Swapping "+i+" with "+j+" : "+B);
                      count++;
                  }
              }
          }
      }