繁体   English   中英

如何使用参数 Math.abs(b)-Math(a) 进行排序

[英]How to sort using parameter Math.abs(b)-Math(a)

我的代码有什么问题? 我收到如下错误:

no suitable method found for sort(int[],<anonymous Comparator<Integer>>)
                 Arrays.sort(ar, new Comparator<Integer>(){
                       ^
    method Arrays.<T#1>sort(T#1[],Comparator<? super T#1>) is not applicable
      (inference variable T#1 has incompatible bounds
        equality constraints: int
        lower 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))
import java.util.*;

public class B {
    public static void main(String[] args) {
 
            Scanner sc = new Scanner(System.in);
            int t = sc.nextInt();

            while(t-->0){

                int n = sc.nextInt(); 
                int ar[] = new int[n];

                for(int  i = 0;i<n;i++)
                    ar[i] = sc.nextInt();;
                
 
                 Arrays.sort(ar, new Comparator<Integer>(){

                    public int compare(int a, int b){
                        return Math.abs(b)-Math.abs(a);
                    }

                });
 
            }

  
        }
}

代码存在多个问题。

我已经修复了语法问题和循环问题。 虽然我不确定比较数字的绝对值你想要达到什么。

import java.util.*;

public class Test {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        Integer ar[] = new Integer[t];

        while (t-- > 0) {
            ar[t] = sc.nextInt();
        }

        Arrays.sort(ar, new Comparator<Integer>() {

            public int compare(Integer a, Integer b) {
                return Math.abs(b) - Math.abs(a);
            }
        });

        for (int i = 0; i < ar.length; i++)
            System.out.println(ar[i]);
    }
}
First execution:
================
4


-100
-9
-1000
-6



-1000
-100
-9
-6
Second execution:
================
6

1
67
12
5
7
34

67
34
12
7
5
1

顺便说一下,这个样本仍然有很多事情需要注意。 说资源关闭,异常处理等。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM