我总是返回1作为比较,但是我没有找到ans

ncgqoxb0  于 2021-06-26  发布在  Java
关注(0)|答案(1)|浏览(210)

关闭。这个问题需要细节或清晰。它目前不接受答案。
**想改进这个问题吗?**通过编辑这个帖子来添加细节并澄清问题。

三天前关门了。
改进这个问题

import java.util.*;
public class S {
    static Scanner sc = new Scanner(System.in);
    static Integer a[] = new Integer[3];

    public static void main(String[] args) {
        int t = sc.nextInt();
        while (t-- > 0) {
            int n=3;
            for (int i = 0; i < n; i++) {
                a[i] = sc.nextInt();
            }
            Arrays.sort(a,new Sort1());
        }
    }
}
class Sort1 implements Comparator<Integer>
{
    public int compare(Integer a,Integer b)

    {
        for(int a1:S.a){
            System.out.print(a1+" ");
        }
        System.out.println();
        // return a-b;
        return 1;
    }
}

嗨,我能解决我的问题。compare tor在java中是如何工作的?输入:1 5 2 7输出5 2 7为什么输出不是7 5 2?如果我们返回1,我就知道了。1.5 2.5 2(由于一次返回)=>2 5 3.7 2 5=>7 5 2

nr7wwzry

nr7wwzry1#

所以你对 Comparator 这是错误的。
从名字本身我们可以假设它需要比较一些东西,对吗?但是在你的代码中,你不是在比较任何东西,而是在comparator中打印错误的值。
如果您检查比较器的参数,您可以看到两个整数正在传递给它。这些整数实际上是数组元素。你需要比较一下那些元素。

public int compare(Integer a,Integer b)
    {
        if(a < b){
            return 1;
        }else if( a == b){
            return 0;
        }
        else {
            return -1;

        }
    }

像这样在主屏幕上打印你的数组。它将被分类

相关问题