In: Computer Science
I need a java code
Write a simple program to prompt the user for a
number between 1 and 12 (inclusive)
and print out the corresponding month. For
example:
The 12th month is December.
Use a java "switch" statement to convert from the
number (1-12) to the month.
Also use a "do while" loop and conditional
checking to validate that the number entered is between 1 and
12
inclusive and if not, prompt the user again until getting the
correct value.
Source code of the program and its working are given below.Comments are also given along with the code for better understanding.Screen shot of the code and output are also attached.If find any difficulty, feel free to ask in comment section. Please do upvote the answer.Thank you.
Working of the code
Source code
//Importing Scanner class to read user input
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
//Creating scanner class object to read user input
Scanner sc = new Scanner(System.in);
//declaring an integer variable monthNumber
int monthNumber;
//loop exit when user enter a valid number
//if the user input is not in the valid range,loop executes its body again
do {
System.out.print("Enter month's number: ");
monthNumber = sc.nextInt();
}while(!(monthNumber>=1 && monthNumber<=12));//condition to repeat the loop
//switch statement compare monthNumber with each case values.Whenever a match
//is found, the statement associate with the match will be executed
switch (monthNumber) {
case 1:
System.out.println("January");
break;
case 2:
System.out.println("February");
break;
case 3:
System.out.println("March");
break;
case 4:
System.out.println("April");
break;
case 5:
System.out.println("May");
break;
case 6:
System.out.println("June");
break;
case 7:
System.out.println("July");
break;
case 8:
System.out.println("August");
break;
case 9:
System.out.println("September");
break;
case 10:
System.out.println("October");
break;
case 11:
System.out.println("November");
break;
case 12:
System.out.println("December");
break;
//if no match found
default:
System.out.println("Invalid entry.");
break;
}
}
}
Screen shot of the code


Screen shot of the output
