The problem
Write a program that randomly generates an integer between 1 and 12 and displays the English month name January, February, ..., December for the number 1, 2, ..., 12, accordingly.
Breaking it down
Java 8 simplifies this task in a couple of ways. First, the date/time api has been completely rewriting to include goodies found in joda. This allows you to use the Month
enum once you have a generated number. Second, we can generate a range of numbers by calling random.ints
. Prior to these features it would of required a case statement and some additional code.
public static void main(String[] strings) {
Random random = new Random();
OptionalInt randomNumberMonth = random.ints(0, 12).findFirst();
String monthAsText = Month.of(randomNumberMonth.getAsInt())
.getDisplayName(TextStyle.FULL, Locale.US);
System.out.println("A random month is: " + monthAsText);
}