删除重复输出

时间:2015-01-18 03:52:36

标签: java hashmap output

我正在开发一个关于Hashmaps的初学Java教程,并提供了以下任务

// Create a method called printOccurrences(int[] scores)
        //
        // HINT: Use a HashMap to keep track of the counts (K: Integer, V: Integer)
        // For int[] scores = {85,93,96,96,92,100,91,85,87,92}
        // Desired Output Is:
        //  85 - 2
        //  87 - 1
        //  92 - 2
        //  93 - 1
        //  96 - 2
        // 100 - 1
        //

以下是我的代码

import java.util.HashMap;

public class Ex5_NumberOfOccurrences {
    public static void main(String[] args) {
        int[] scores = {85,93,96,96,92,100,91,85,87,92};
        printOccurrences(scores);
    }
        public static void printOccurrences (int[] scores){
            HashMap <Integer, Integer> tracker = new HashMap<Integer, Integer>();
            for (int i = 0; i < scores.length; i++){
                int count = 0;
                for (int j =  0; j< scores.length; j++){
                    if (scores [i] == scores[j]){
                        count ++;
                    }   
                }
            tracker.put(scores[i], count);

            System.out.println( scores[i] + "-" + tracker.get(scores[i]));
            }           
        }
}

代码运行,但我的输出有重复值,如下所示。

85-2
93-1
96-2
96-2
92-2
100-1
91-1
85-2
87-1
92-2

有谁知道如何避免重复的输出值?

2 个答案:

答案 0 :(得分:1)

在每次迭代时打印跟踪器输出,这会导致重复输出。 HashMap存储了正确的值。

您可以尝试(在for循环之外):

for (int key : tracker.keySet())
  System.out.println(key + "-" + tracker.get(key));

此外,您可以使用fortracker)代替使用多个HashMap循环来跟踪:

for (int score : scores) {
  if (tracker.constainsKey(score))
    tracker.put(score, tracker.get(score) + 1);
  else
    tracker.put(score, 1); //Init for each score

答案 1 :(得分:0)

由于println位于外部for循环中,因此每次在score数组中点击值时都会打印结果。

我认为更多的是问题的精神,试着像这样重写:

for each score - 
   if the map has the score key - 
     pull the value out of the map and increment it, return it to the map
   else 
     insert into the map (key, 1)

不同之处在于,这将为您提供线性性能而不是二次性(即此版本将在时间上与输入数组的长度成比例,因为您只扫描数组一次,而您的版本将运行时间与数组长度的平方成正比。)

相关问题