有 Java 编程相关的问题?

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

排序功能没有排序!JAVA

下面是我用Java编写的测验程序中的代码块。我正在尝试将高分读取/写入文件,并对高分表进行排序

public static void main(String[] args) throws IOException {

        sort(highscoreTable);
        int score1 = 0;
        int score2 = 0;
        int totalscore = 0;
        int NumberofQuestions = 5;

        // RECORDS TO STORE QUESTION, ANSWER WOULD BE HERE //

private static void start(int NumberofQuestions, String[] Answers, String[][] questions, int score1, int score2, int totalscore) throws IOException {
        // DISPLAYED ON THE HOME SCREEN SO USER CAN CHOOSE WHAT THEY WANT TO DO
        System.out.println("[0] Leave\n");
        while(true) {
            System.out.println("[1] Play");
            System.out.println("[2] Highscore");
            System.out.print("Enter Choice: ");
            String useranswer = scanner.nextLine();
            System.out.println();
            if (useranswer.equals("1")) {
                mainLoop(NumberofQuestions, Answers, questions, score1, score2, totalscore);
            } else if (useranswer.equals("2")) {
                sort(highscoreTable);
            } else if (useranswer.equals("0")) {
                try {
                    save();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            }
        }
    }

我想先在屏幕上显示这个位,如果用户按2,我想编程读取文件并显示以前的高分

 public static void save() throws IOException {

        String aggFileName = "agg-"+String.valueOf("06.txt");
        FileWriter fstream = new FileWriter(aggFileName);
        BufferedWriter out = new BufferedWriter(fstream);

        for (Map.Entry<String, String> entry : highscoreTable.entrySet()) {
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); //this statement prints out my keys and values
            out.write(entry.getKey() + "--" + entry.getValue() + "\n");
            System.out.println("Done");
            out.flush();   // Flush the buffer and write all changes to the disk
        }

        out.close();    // Close the file
    }

save方法非常有效,我对它没有任何问题

public static void mainLoop(int NumberofQuestions, String[]Answers, String[][] questions, int score1, int score2, int totalscore) throws IOException {

// USER WOULD ANSWER QUESTIONS HERE
        addHighscore(name, totalscore);
    }

public static void addHighscore(String name, int totalscore) throws IOException {
        highscoreTable.put(String.valueOf(totalscore), name);
    }

这里的函数将用户名和总分添加到树状图中

public static void highscoreImport(HashMap highscoreTable) throws IOException {

        String filePath = "agg-06.txt";
        String line;
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        while ((line = reader.readLine()) != null)
        {
            String[] parts = line.split("--", 2);
            if (parts.length >= 2)
            {
                String key = parts[0];
                String value = parts[1];
                highscoreTable.put(key, value);
            } else {
            }
        }
        for (Object key : highscoreTable.keySet())
        {
            System.out.println(key + "--" + highscoreTable.get(key));
        }

        reader.close();

    }

这是我遇到问题的部分。我希望程序从文件中获取信息,现在将其与来自用户最近测验的数据合并,然后对分数进行排序(我想要一个高分表),这样当用户键入“2”以查看高分表时,它将按降序排列

public static void sort(HashMap highscoreTable) throws IOException {

        System.out.println("Before Sorting:");
        Set set = highscoreTable.entrySet();
        Iterator iterator = set.iterator();
        while(iterator.hasNext()) {
            Map.Entry me = (Map.Entry)iterator.next();
            System.out.print(me.getKey() + ": ");
            System.out.println(me.getValue());
        }
        Map<Integer, String> map = new TreeMap<Integer, String>(highscoreTable);
        System.out.println("After Sorting:");
        Set set2 = map.entrySet();
        Iterator iterator2 = set2.iterator();
        while(iterator2.hasNext()) {
            Map.Entry me2 = (Map.Entry)iterator2.next();
            System.out.print(me2.getKey() + ": ");
            System.out.println(me2.getValue());
        }
    }

这里,“之前”和“之后”排序输出的列表是相同的未排序列表


很抱歉读了这么长时间,如果有人能帮我解决这个问题,我将不胜感激


共 (2) 个答案

  1. # 1 楼答案

    因为在addHighscore方法中,您正在执行以下操作:

    highscoreTable.put(String.valueOf(totalscore), name);
    

    我假设它是Map<String, String>(键和值类型都是String

    但是在sort方法中,您确实

    Map<Integer, String> map = new TreeMap<Integer, String>(highscoreTable);
    

    如果正确定义了highscoreTable的类型,则TreeMap实例化在编译时应该失败。如果不是,并且构造函数TreeMap(Map)按照其键的自然顺序进行排序(参见Javadoc),它可能是按照String顺序或其他顺序对其进行排序。所以“111”之前会出现“12”等意想不到的结果。最好在所有集合和其他泛型类型类中定义类型

  2. # 2 楼答案

    问题在于分数的类型。您正在将分数作为字符串插入。第二个小问题是排序顺序应该颠倒

    请看以下示例:

    public class Test {
    
    public static void main(String[] args) throws IOException {
        System.out.println("String scores:");
        HashMap<String, String> scores = new HashMap<>();
        scores.put("12", "John");
        scores.put("240", "Mary");
        scores.put("14", "Sean");
        scores.put("35", "Pat");
    
        sort(scores);
        System.out.println();
    
        System.out.println("Integer scores:");
        HashMap<Integer,String> integerScores = new HashMap<>();
        integerScores.put(12, "John");
        integerScores.put(240, "Mary");
        integerScores.put(14, "Sean");
        integerScores.put(35, "Pat");
    
        sort(integerScores);
    }
    
    public static void sort(HashMap highscoreTable) throws IOException {
    
        System.out.println("Before Sorting:");
        Set set = highscoreTable.entrySet();
        Iterator iterator = set.iterator();
        while(iterator.hasNext()) {
            Map.Entry me = (Map.Entry)iterator.next();
            System.out.print(me.getKey() + ": ");
            System.out.println(me.getValue());
        }
        Map<Integer, String> map = new TreeMap<Integer, String>(Collections.reverseOrder());    // Descending
        map.putAll(highscoreTable);
        System.out.println("After Sorting:");
        Set set2 = map.entrySet();
        Iterator iterator2 = set2.iterator();
        while(iterator2.hasNext()) {
            Map.Entry me2 = (Map.Entry)iterator2.next();
            System.out.print(me2.getKey() + ": ");
            System.out.println(me2.getValue());
        }
    }
    

    }

    本例使用“分数”和“整数核心”的排序方法。 以下是排序后的输出: 字符串分数: 35:Pat 240:玛丽 14:Sean 12:John

    整数分: 240:玛丽 35:Pat 14:Sean 12:John

    你可以在第一类中看到35在240之前,因为3在2之前。它正在进行字符串排序。第二种排序是按整数的值排序。一旦理解了这一点,就很容易修复代码

    原始代码将键作为字符串插入:

    highscoreTable.put(key, value);
    

    键应为整数:

    highscoreTable.put(Integer.valueOf(key), value);
    

    还请注意,提供的答案可以轻松运行。它包括数据(比附加文件更简单)和输出。当问题以这种方式格式化时,更容易获得帮助