The output from the program is shown here:
Here are all apple constants and their ordinal values:
Jonathan 0
GoldenDel 1
RedDel 2
Winesap 3
Cortland 4
GoldenDel comes before RedDel
RedDel equals RedDel
RedDel equals RedDel
RedDel == RedDel
Another Enumeration Example
Before moving on, we will look at a different example that uses an enum. In Chapter 9, an
automated "decision maker" program was created. In that version, variables called NO,
YES, MAYBE, LATER, SOON, and NEVER were declared within an interface and used to
represent the possible answers. While there is nothing technically wrong with that approach,
the enumeration is a better choice. Here is an improved version of that program that uses an
enum called Answers to define the answers. You should compare this version to the original
in Chapter 9.
//
An improved version of the "Decision Maker"
//
program from Chapter 9. This version uses an
//
enum, rather than interface variables, to
//
represent the answers.
import java.util.Random;
// An enumeration of the possible answers.
enum Answers {
NO, YES, MAYBE, LATER, SOON, NEVER
}
class Question {
Random rand = new Random();
Answers ask() {
int prob = (int) (100 * rand.nextDouble());
if (prob < 15)
return Answers.MAYBE;
// 15%
else if (prob < 30)
return Answers.NO;
// 15%
else if (prob < 60)
return Answers.YES;
// 30%
else if (prob < 75)
return Answers.LATER;
// 15%
else if (prob < 98)
return Answers.SOON;
// 13%
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home