In: Computer Science
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"};
Have a look at the below code. I have put comments wherever required for better understanding.
import java.util.*;
class Main {
public static void main(String[] args) {
// create scanner object
Scanner sc = new Scanner(System.in);
/// create array for months name
String[] arr = {"January","February","March","April","May","June","July","August","September","October","November","December"};
// create variable for char and int
char choice;
int month;
char xyz = 'N';
// run a while loop
while(true){
while (true){
System.out.print("Enter the Month of the Year: ");
month = sc.nextInt();// take month input
if(month>=0 && month<12){ // validate month
// print month name
System.out.println("The month name is " + arr[month-1]);
break;
}
else{
System.out.println("Invalid Entry");
break;
}
} // check if to continue or not
System.out.print("Try again (Y/N): ");
choice = sc.next().charAt(0);// take choice input
if (choice==xyz){
System.out.println("Done");
break;
}
}
}
}
Happy Learning!