3.1.1

question:

Write a client that creates a symbol table mapping letter grades to numerical scores, as in the table below, then reads from standard input a list of letter grades and computes and prints the GPA (the average of the numbers corresponding to the grades).

answer:

import edu.princeton.cs.algs4.*;

public class GPA
{
    public static void main(String[] args)
    {
        ST<String, Double> st = new ST<String, Double>();
        st.put("A+", 4.33);
        st.put("A", 4.00);
        st.put("A-", 3.67);
        st.put("B+", 3.33);
        st.put("B", 3.00);
        st.put("B-", 2.67);
        st.put("C+", 2.33);
        st.put("C", 2.00); 
        st.put("C-", 1.67);
        st.put("D", 1.00);
        st.put("F", 0.00);
        double sum = 0;
        int n = 0;
        while(!StdIn.isEmpty())
        {
            String grade = StdIn.readString();
            sum += st.get(grade);
            n++;
        }
        StdOut.println(sum/n);
    }
}

猜你喜欢

转载自www.cnblogs.com/w-j-c/p/9154422.html