有 Java 编程相关的问题?

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

排序如何使用文件中的名称对高分列表进行排序?JAVA

我正在尝试对我的java蛇游戏的高分进行排序:我希望能够从文件中对它们进行排序

该文件的一个示例是:

  1. 乔治:200
  2. 莎拉:700
  3. 本:100
  4. 弗雷德:400
  5. AJ:300

我如何将名称和所有内容排序为:

  1. 莎拉:700
  2. 弗雷德:400
  3. AJ:300
  4. 乔治:200
  5. 本:100

如果你能解释如何做到这一点,发送一些代码,如果你以前做过,或发送给我一个链接,解释它很好,那将是伟大的!!谢谢


共 (2) 个答案

  1. # 1 楼答案

    你需要一个最大堆

    1. 逐行读取文件中的所有值。读取时,请使用拆分函数按以下方式拆分:。这会给你一个名字,后面跟着分数。创建一个对象,其中id是score,value是包含score和name的对象。(你确实需要考虑相同的分数)

      字符串[]值=输入。分裂(“:); 字符串名称=值[0]; 字符串分数=值[1]

    2. 创建一个max堆并将元素逐个插入堆中。 在java中,您可以将PriorityQueue对象用于此数据结构

    3. 完成后,继续逐个弹出元素。这将按降序显示所有元素。由于对象同时包含分数和名称,因此可以使用它按降序打印结果

    使用PriorityQueue的“poll”方法来实现这一点

    http://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html

  2. # 2 楼答案

    正如我的评论所述:

    逐行读取输入文件,将regex表达式匹配的值存储到TreeMap(排序的HashMap,在本例中是反向排序的),然后按正确的顺序将这些值写回文件

    输入:“scores.txt”:

    1.  George : 200
    2.  Sarah : 700
    3.  Ben : 100
    4.  Fred : 400
    5.  AJ : 300
    

    输出:

    1.  Sarah : 700
    2.  Fred : 400
    3.  AJ : 300
    4.  George : 200
    5.  Ben : 100
    

    import java.util.*;
    import java.util.regex.*;
    import java.io.*;
    
    public class regex {
        public static void main(String args[]) throws java.io.IOException {       
            File file = new File("scores.txt");
            Scanner scan = new Scanner(file);
    
            //create a TreeMap in reverse order otherwise it will sort ascending instead of descending
            Map<Integer, String> map = new TreeMap<Integer, String>(Collections.reverseOrder());
    
            String regexp = "\\d*\\.\\s*([a-zA-Z]*)\\s*\\:\\s*(\\d*)";
            Pattern pattern = Pattern.compile(regexp);
    
            while(scan.hasNextLine()) {
                Matcher match = pattern.matcher(scan.nextLine());
                while (match.find()) {  
                    //insert into the map the score : name  ->  (\\d*) : ([a-zA-Z]*)
                    map.put(Integer.parseInt(match.group(2)), match.group(1));
                }
            }
    
            BufferedWriter bw = new BufferedWriter(new FileWriter(file));
    
            int count = 1;
            for (Map.Entry entry : map.entrySet()) {
                //writes ->       1. George : 100 \n
                bw.write(count + ".  " + entry.getValue() + " : " + entry.getKey() + "\n");
                count++;
            }   
    
            bw.close();
        }
    }