使用键映射到一系列值。字母成绩到考试成绩示例

时间:2015-11-09 23:54:57

标签: java hashmap

正如标题所暗示的那样。我需要等级" A"返回90-100之间的任何分数。或者在这种情况下,用户根据曲线或其他东西决定设置的截止值。这就是我所拥有的,但我无法想办法让它做我想做的事。

private HashMap<String, Double> letterGrade = new HashMap<String, Double>();

public void setgradeCutOff(String[] letterGrades, double[] cutoffs) {
        for(int i = 0; i < letterGrades.length; i++){
            letterGrade.put(letterGrades[i], cutoffs[i]);
        }

    }
public String getGrade(String studentName) {
    //Returns a student's average score for all exams
    double averageScore = getAverageExamGrade(studentName);
    for(Entry<String, Double> entry : letterGrade.entrySet()){
        if(entry.getValue() == averageScore){
            return entry.getKey();
        }
    }
    return null;
}

仅当averageScore恰好是截止值之一时才有效。如何修改它以使字符串键映射到setGradeCutOff方法指定的范围?

这就是我期望它发挥作用的方式:

setLetterGradesCutoffs(new String[]{"A","B","C","D","F"}, 
                   new double[] {85,70,60,50,0});

Laura. Average exam score: 87 Grade: A
Peter. Average exam score: 72 Grade: B
Miranda. Average exam score: 67 Grade: C

2 个答案:

答案 0 :(得分:3)

不需要第三方库,TreeMap可以使用floorEntry()方法(Java 6 +)来实现:

private static TreeMap<Double, String> gradeMap = new TreeMap<>();
static {
    gradeMap.put(85.0, "A");
    gradeMap.put(70.0, "B");
    gradeMap.put(60.0, "C");
    gradeMap.put(50.0, "D");
    gradeMap.put( 0.0, "F");
}
private static void printGrade(double score) {
    System.out.printf("Average exam score: %s Grade: %s%n",
                      NumberFormat.getInstance().format(score),
                      gradeMap.floorEntry(score).getValue());
}

测试

public static void main(String[] args) {
    printGrade(87);
    printGrade(72);
    printGrade(67);
    printGrade(69.99);
    printGrade(70.00);
    printGrade(70.01);
}

输出

Average exam score: 87 Grade: A
Average exam score: 72 Grade: B
Average exam score: 67 Grade: C
Average exam score: 69.99 Grade: C
Average exam score: 70 Grade: B
Average exam score: 70.01 Grade: B

答案 1 :(得分:1)

您可以使用Guava的RangeMap将成绩范围映射到一封信:

RangeMap<Integer, String> gradeLetter = ImmutableRangeMap.builder()
    .put(Range.closed(90, 100), "A")
    .put(Range.closed(60, 89), "B")
    // ...
    .build();

public String getGrade(String studentName) {
    int averageScore = getAverageExamGrade(studentName);
    return gradeLetter.get(averageScore);
}