gpt4 book ai didi

java - 解决难题,数组编程,java

转载 作者:行者123 更新时间:2023-12-02 06:14:43 25 4
gpt4 key购买 nike

我有一个问题:我无法检查两个数组 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++;
}
}
}
}

漏洞程序是... 导入java.util.ArrayList; 导入java.util.Collections; 导入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");
}
}

顺便说一句:我正在使用 Netbeans。

最佳答案

这与 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++;
}
}
}
}

关于java - 解决难题,数组编程,java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21600099/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com