Course Links

Exercises

Resources

External

Background

Enumerated types have been a feature of C and C++ for a long time, but were only added to Java in version 5.0. Nevertheless, they are useful because they can make your programs more readable and easy to debug. Oracle has an excellent description of Java's enumerated types on its web site, and the reader is referred there for the basics.

Having read the description of enumerated types at least as far as the Planet example, here's how to think of Java's enum: It is a specialized form of class of which only a fixed number of instances exist, all predefined. In other ways, it acts much as any other class -- you can call a method on an enum instance just like an instance of any other class (if you have defined any methods for it in the first place).

Exercise

Create an enumerated type for grades at Smith, in the style of the Planet example. You should have one instance for each possible grade, with a field for the value the grade contributes towards the GPA (4.0 for A, 3.7 for A-, 3.3 for B+, etc.), and another for the string representation of the grade. (Note that you can't use A+ as an enumerated constant because it is not a valid variable name; you will have to use something like APLUS or A_PLUS instead, leading to the need for a printable representation. You should also write a static method that will compute the gpa of an array of grades, and a toString() method.

Now create a tester class, TestGrade. Add a main() method that creates an ArrayList of grades, prints it, and then prints out the computed GPA. The output should look something like this:

List of grades:  [A-, B+, A, A-]
Average GPA:  3.7