Java Program to pick random value from enumerations
Program
import java.util.Random;
public class RandomAnswers
{
public enum Answers{
NO, YES, MAYBE, LATER, SOON, NEVER
}
public static void main(String[] args)
{
final Answers[] VALUES = Answers.values();
final int SIZE = VALUES.length;
final Random RANDOM = new Random();
System.out.println(VALUES[RANDOM.nextInt(SIZE)]);
}
}
This program demonstrates how to pick a random value from an enumeration (enum) in Java.
-
Enumeration
Answers:- The
Answersenum defines six possible values:NO,YES,MAYBE,LATER,SOON, andNEVER. - Enumerations in Java are a special type of class that represents a group of constants.
- The
-
Main Method:
- The program uses the
main()method to randomly pick and display one of the values from theAnswersenum.
- The program uses the
-
Steps in
main()Method:- Retrieve All Enum Values:
Answers.values()returns an array containing all the constants in theAnswersenum ([NO, YES, MAYBE, LATER, SOON, NEVER]).- The array is stored in the
VALUESvariable.
- Find the Number of Constants:
VALUES.lengthgets the total number of constants in the enum, which is stored in theSIZEvariable.
- Generate a Random Index:
- A
Randomobject is created usingnew Random(). - The method
RANDOM.nextInt(SIZE)generates a random integer between0(inclusive) andSIZE(exclusive). This ensures the index is valid for theVALUESarray.
- A
- Pick a Random Value:
- A random constant from the
VALUESarray is selected using the generated index and printed to the console.
- A random constant from the
- Retrieve All Enum Values:
Each time the program runs, the output might differ because the value is chosen randomly.
-
Enums in Java:
- Enums are used to define a fixed set of constants.
- The method
values()returns an array of all the enum constants.
-
Using
RandomClass:- The
Randomclass is used to generate random numbers. - The
nextInt(SIZE)method generates a random integer between0(inclusive) andSIZE(exclusive), which is perfect for indexing the array of enum constants.
- The
-
Accessing Enum Values:
- The program accesses an enum constant by using its index in the array returned by
values().
- The program accesses an enum constant by using its index in the array returned by
Advantages of Using Enums:
- Enums ensure type safety by restricting the values to the predefined constants.
- They make the code more readable and maintainable compared to using plain strings or integers.
Output
$ java RandomAnswers
YES
$ java RandomAnswers
NO
$ java RandomAnswers
NEVER
$ java RandomAnswers
LATER