Create an enumeration named Month that holds values for the months of the year. With JANUARY equal to 1, FEBRUARY equal to 2, and so on through DECEMBER equal to 12. Write a program named MonthNames that prompts the user for a month integer. Convert the user’s entry to a Month value, and display it. Make sure your integer prompt message does not contain any month names (January, etc.) as this will cause the tests to fail! For Example: "Enter a month number >> " does not contain month names and will work properly.

Respuesta :

Answer:

import java.util.Scanner;

public class Question {    

   public enum Months{

       JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER

   }

   public static void main(String args[]) {

     

     Scanner scan = new Scanner(System.in);

     System.out.println("Enter a month number>>: ");

     int inputNumber = scan.nextInt();

     

     if(inputNumber > 12 || inputNumber < 1){

         System.out.println("Please enter a valid number.");

     } else {

         System.out.println(Months.values()[inputNumber - 1]);

     }

   }

}

Explanation:

The import statement at the top of the class is to help us receive user input via the keyboard. The class was defined named "Question". Then the enum was declared listing all the months. Then the main function was declared. The Scanner object was created as scan, then the user is prompted for input which is assigned to inputNumber. The user input is validated to be within the range of 1 - 12; if it is outside the range, the user shown an error message. If the input is correct, the appropriate month is displayed to the user. To get the appropriate month, we subtract one from the user input because the enum class uses the zero-index counting; it start counting from zero.