0

こんにちは、Stackoverflow genii です。キーではなく値で TreeMap をソートする方法について質問があります。これは課題のためなので、このようにしなければなりません。誰かに答えを入力してもらう必要は必ずしもありません。私が間違っていることについてのヒントだけです。これが私のコードです:

import java.security.KeyStore.Entry;
import java.util.Scanner;
import java.util.TreeMap;

public class Assignment2 {
    public static void main(String[] args) {
            int x = 10;
            if(args.length > 0) {
                    x = Integer.parseInt(args[0]);
            }
            Scanner in = new Scanner(System.in);
             TreeMap<String, Integer> t = new TreeMap<>();

             while(in.hasNext()) {
                     String k = in.next();   
                     Integer cur = t.get(k);
                     t.put(k, cur == null ? 1 : cur +1);
             }

             in.close();

            //Printing: iterate through two nested for loops, 

             int curmax = 0;
             String curstring = null;
             for(int i=0; i<x; i++){
                     for (java.util.Map.Entry<String, Integer> e : t.entrySet()) {
                             if(e.getValue() > curmax)
//if the value of e is bigger then the last maximum, set the maximum equal to the value. 
                                     curmax = e.getValue();
                                     curstring = e.getKey();
                     }

                     System.out.printf("%d %s\n", curmax, curstring);

   //Switched order of printing since that's what the example result does.
                         t.remove(curstring);
                        curmax =0;
                 }
        }
}
4

0 に答える 0