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"};
CODE -
import java.util.Scanner;
public class MonthNames {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
// Creating array of string and initializing it with month names
String MONTHS[] = {"January","February","March","April","May","June","July","August","September","October","November","December"};
char choice;
int month;
// Do-while loop to run until user enters N to exit
do {
// Taking month as input from user
System.out.print("Enter the Month of the Year: ");
month = keyboard.nextInt();
// Adjust the month no. entered by user to match with index of MONTHS array
month--;
// Display error message if user entered invalid month no.
if (month > 11 || month <0)
System.out.println("Invalid Entry");
// Display the month name
else
System.out.println("The Month name is " + MONTHS[month] + ".");
// Prompting user to continue
System.out.print("Try again (Y/N): ");
choice = keyboard.next().charAt(0);
} while (choice != 'N');
// Displaying "Done" after loop has ended
System.out.println("Done");
keyboard.close();
}
}
SCREENSHOTS -
CODE -
OUTPUT -
If you have any doubt regarding the solution, then do
comment.
Do upvote.
Get Answers For Free
Most questions answered within 1 hours.