簡體   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