有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java整数数组排序

我这里有一段代码,它获取一个文件并将其放入一个数组中。我现在需要做的是将第二列中的整数从大到小排序。这是我的代码,底部有一个指向数据文件的链接。我知道有排序算法,但我不知道如何实现它们

import java.util.*;
import java.io.*;
public class sorter{
public static int id = 0;
public static int score = 0;
public static void main(String args[]){
Scanner inFile = null;
          try {
  inFile = new Scanner (new File ("sorter.txt"));
 } catch (FileNotFoundException e) {
  System.out.println("File not found!");
  System.exit(0); 
    } 
 while (inFile.hasNextLine()){
    String str = inFile.nextLine();
    String [] parts = str.split(" ");
    String part1 = parts[0];
    String part2 = parts[1];
    id = Integer.parseInt(part1);
    score = Integer.parseInt(part2);
    System.out.println(part1 + "  " +part2);
}
 }
  }

以下是输出的内容:

 /*
ID​  Score
305​ 265
306​ 262
115 ​257
311 ​256
123 ​253
116​ 246
325 ​246
321 ​245
323 ​245
113 ​243
218 ​243
208 ​242
302 ​242
112 ​239
104 ​239
110 ​238
223 ​230
213​ 229
207 ​228
203 ​224
222 ​223
    */

Link to data file


共 (1) 个答案

  1. # 1 楼答案

    我会创建一个类来处理这个问题

    class Data {
        private int id;
        private int score;
    
        //constructor and other stuff
    }
    

    既然有了这个,就创建一个^{}来保存所有数据

    List<Data> list = new ArrayList<>();
    while (inFile.hasNextLine()){
        String str = inFile.nextLine();
        String [] parts = str.split(" ");
        list.add(Integer.parseInt(parts[0]), Integer.parseInt(parts[1]));
    }
    

    现在你有了这个列表,你可以对它进行排序了。但是怎么做呢

    这是救援的API!在^{}类(称为^{})中有一个方法,允许您使用自定义的^{}对列表进行排序

    所以你需要的是创建一个比较器,它将根据你的物体的分数来比较它们:

    static class DataComparator implements Comparator<Data> {
         @Override
         public int compare(Data d1, Data d2){
             return Integer.compare(d1.getScore(), d2.getScore());
         }
     }
    

    现在你有了这些,只需调用^{

    Collections.sort(list, new DataComparator());