001package algs25;
002import stdlib.*;
003import java.util.Arrays;
004/* ***********************************************************************
005 *  Compilation:  javac Grade.java
006 *  Execution:    java Grade
007 *
008 *  Illustrates implementation of Comparable interface
009 *
010 *************************************************************************/
011
012public class XGrade implements Comparable<XGrade> {
013        private final String grade;
014
015        public XGrade(String grade) {
016                this.grade = grade;
017                if (gpa() < 0.0) throw new Error("Illegal grade");
018        }
019
020        public double gpa() {
021                if (grade.equals("A"))  return 4.00;
022                if (grade.equals("B"))  return 3.00;
023                if (grade.equals("C"))  return 2.00;
024                if (grade.equals("D"))  return 1.00;
025                if (grade.equals("F"))  return 0.00;
026                if (grade.equals("B+")) return 3.33;
027                if (grade.equals("C+")) return 2.33;
028                if (grade.equals("A-")) return 3.67;
029                if (grade.equals("B-")) return 2.67;
030                if (grade.equals("C-")) return 1.67;
031                return -1.0;
032        }
033
034        public int compareTo(XGrade w) {
035                XGrade v = this;
036                if (v.gpa() < w.gpa()) return -1;
037                if (v.gpa() > w.gpa()) return +1;
038                return 0;
039        }
040
041        // use %-2s flag to left justify
042        public String toString() {
043                return String.format("%-2s %3.2f", grade, gpa());
044        }
045
046
047        // test client
048        public static void main(String[] args) {
049                XGrade[] grades = new XGrade[8];
050                grades[0] = new XGrade("B+");
051                grades[1] = new XGrade("A");
052                grades[2] = new XGrade("C+");
053                grades[3] = new XGrade("B-");
054                grades[4] = new XGrade("A-");
055                grades[5] = new XGrade("D");
056                grades[6] = new XGrade("F");
057                grades[7] = new XGrade("A-");
058
059
060                StdOut.println("Unsorted");
061                for (XGrade grade2 : grades)
062                        StdOut.println(grade2);
063                StdOut.println();
064
065                StdOut.println("Sorted");
066                Arrays.sort(grades);
067                for (XGrade grade2 : grades)
068                        StdOut.println(grade2);
069        }
070
071}
072
073