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 - 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"};
import java.util.*;
public class Main {
public static void main(String[] args) {
String[] months={"January","February","March","April","May","June","July","August","September","October","November","December"};
Scanner myKeyboard =new Scanner(System.in);
String choice="";
while(true){
System.out.print("Enter the month of the year: ");
int n=myKeyboard .nextInt();
if(n>12 || n<1)
System.out.println("Invalid Entry");
else
System.out.println("The month name is "+months[n-1]);
System.out.println("Try Again(Y/N)");
choice=myKeyboard .next();
if(choice.compareTo("N")==0)
break;
}
System.out.println("Done");
}
}
Feel free to ask.
Kindly Upvote. ?
Get Answers For Free
Most questions answered within 1 hours.