In: Computer Science
Using Eclipse IDE
Create a Java Program/Class named MonthNames that will display the Month names using an array.
1. Create an array of string named MONTHS and assign it the values "January" through "December". All 12 months need to be in the array with the first element being "January", then "February", etc.
2. Using a loop, prompt me to enter an int variable of 1-12 to display the Month of the Year. Once you have the value, the program needs to adjust the given input to align with the array index and then confirm that the variable is in the range of 0-11. If it is not, display "Invalid Entry". If it is in range, display the string the matches the given entry. Then prompt to continue.
Tip:For the String input for the Prompt to Continue - it is preferable to use .next() instead of .nextLine(). Otherwise you will run into the Scanner Bug described in Section 3.10.
3. Display "Done" after the loop processing has ended.
Enter the Month of the Year: 1
The month name is January
Try again (Y/N): Y
Enter the Month of the Year : 2
The Month name is February.
Try again (Y/N): Y
Enter the Month of the Year : 55
Invalid Entry
Try again (Y/N): N
You can copy the code below to seed your array.:
{"January","February","March","April","May","June","July","August","September","October","November","December"};
*******************Summary********************
The program for above question is given below with comments and output...
I have used do while loop for running the code repeatedly....
The explanation is in the comments....
I hope it works for you !!!!!!!!!!!!!!!
Ask for any help if needed....happy to help :)
*******************Program*********************
MonthNames.java
import java.util.Scanner;
public class MonthNames
{
public static void main(String[] args)
{
String[] months={"January","February","March","April","May","June","July","August","September","October","November","December"}; //storing months names in array
String ch; //string for storing a char if user wants to continue
Scanner sc=new Scanner(System.in); //Scanner object to take input from user
do //do while loop to run the code repeatedly
{
System.out.print("\nEnter the Month of Year : "); //asking for user to enter month number
int month=sc.nextInt(); //taking input and storing in month
month=month-1; //decrementing value of month by1 to get a value between 0-11
if(month>=0 && month<=11) //if month number is correct
System.out.println("The Month Name is "+months[month]); //then print month name
else //otherwise
System.out.println("Invalid Entry"); //print Invalid entry
System.out.print("Try Again (Y/N) : "); //asking if user wants to continue
ch=sc.next(); //taking input
}while(ch.equals("Y")); //checking if ch equals to Y ...if user entered Y when asked for continue...then run the loop again
System.out.println("Done"); //print done when user is done entering months
}
}
*************************Output*****************************