uses an enum, rather than interface variables, to represent the answers. : enum « Data Type « Java Tutorial






import java.util.Random;

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%
    else
      return Answers.NEVER; // 2%
  }
}

class AskMe {
  static void answer(Answers result) {
    switch (result) {
    case NO:
      System.out.println("No");
      break;
    case YES:
      System.out.println("Yes");
      break;
    case MAYBE:
      System.out.println("Maybe");
      break;
    case LATER:
      System.out.println("Later");
      break;
    case SOON:
      System.out.println("Soon");
      break;
    case NEVER:
      System.out.println("Never");
      break;
    }
  }

  public static void main(String args[]) {
    Question q = new Question();
    answer(q.ask());
    answer(q.ask());
    answer(q.ask());
    answer(q.ask());
  }
}








2.43.enum
2.43.1.Enumeration Fundamentals
2.43.2.How to define an enumeration
2.43.3.Enums in a Class
2.43.4.equals and = operator for enum data type
2.43.5.Comparing Enumeration Values
2.43.6.Two enumeration constants can be compared for equality by using the == relational operator
2.43.7.uses an enum, rather than interface variables, to represent the answers.
2.43.8.enum type with its own method
2.43.9.Enum type field
2.43.10.enum with switch