gpt4 book ai didi

java - 找不到合适的排序方法,推断数组变量具有不兼容的边界

转载 作者:行者123 更新时间:2023-11-29 04:20:10 26 4
gpt4 key购买 nike

该函数尝试将数组转换为钟摆形式。比如输入是:

1 3 2 5 4

答案应该是:

5 3 1 2 4

最小值介于两者之间。

public static void printPendulum(int[] arr, int n){
Arrays.sort(arr);
int noOfRotations = n/2;
for(int i=0;i<noOfRotations;i++){
int temp = arr[n-1];
for(int j=n-1;j>0;j--){
arr[j] = arr[j-1];
}
arr[0] = temp;
}
int temparr[] = new int[noOfRotations-1];
for(int i=0;i<noOfRotations-1;i++)
temparr[i] = arr[i];
Comparator<Integer> comp = Collections.reverseOrder();
Arrays.sort(temparr, comp);
for(int i=0;i<noOfRotations-1;i++)
arr[i] = temparr[i];
for(int i=0;i<n;i++)
System.out.print(arr[i] + " ");
System.out.println();
}

编译错误如下:

    prog.java:36: error: no suitable method found for sort(int[],Comparator<Integer>)
Arrays.sort(temparr, comp);
^
method Arrays.<T#1>sort(T#1[],Comparator<? super T#1>) is not applicable
(inference variable T#1 has incompatible bounds
equality constraints: int
upper bounds: Integer,Object)
method Arrays.<T#2>sort(T#2[],int,int,Comparator<? super T#2>) is not applicable
(cannot infer type-variable(s) T#2
(actual and formal argument lists differ in length))
where T#1,T#2 are type-variables:
T#1 extends Object declared in method <T#1>sort(T#1[],Comparator<? super T#1>)
T#2 extends Object declared in method <T#2>sort(T#2[],int,int,Comparator<? super T#2>)
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error

最佳答案

使用

Integer temparr[] = new Integer[noOfRotations-1];

代替

int temparr[] = new int[noOfRotations-1];

关于java - 找不到合适的排序方法,推断数组变量具有不兼容的边界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49879550/

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