Beginners Programs :

Java Code Display Number to Corresponding Month Name | Java Programs

Write a java program to display month name according to the number, Java month getDisplayName. Here the Java program to display the month name based on the input numbers between 1 to 12 as year consists of 12 months

To arrive at a solution for any given problem, there is a systematic way to solve so that, we can avoid confusion at any stage and reach the expected output with ease.

Firstly, we have to understand the problem statement thoroughly and observe if any specified constraints are given. Then, we determine all the inputs required to solve along with deciding on the expected output as well. Later, we come up with the logic by using these inputs to get our expected output.

Our problem here is to find the name of the month for a given integer number. To solve this, we require the integer number (n) for which the month has to be found. Our expected output is a string representing the name of the month.

To acquire the input number (n), we can make use of Scanner class in Java. This allows us to read the input of any primitive datatype from the console screen at runtime. To make use of this class, we need to first create an object instantiating it and then, with help of this object call the method of the class based on our input type. Here, since our input is an integer, our choice of method to be used would be nextInt().

Prior this, we create a static variable of an array of strings (s).

This is an array consisting all the names of months in order from index 0 to 11 having names from January to December as follows along with the 12th index position containing “InvalidNumber”:

So after getting our input integer number (n) using Scanner class, we make a method call of a static method (monthName1) by passing this input as argument. This method consists of the main logic for reaching the desired output.

Here, we first check whether the number is between 1-12 both inclusive. If this condition is satisfied then, the method returns the (n-1)th index string from the array of strings (s). Since the indexing is from zero so, we return the (n-1)th value.

if(n>=1 && n<=12)

return MonthName.s[n-1];

Else, if the condition is not satisfied and the number is not within the specified range it means that, the entered input number is invalid because there are only 12 months in a year.

Under this situation, we return the value at the 12th index of the array of strings (s) i.e., “InvalidNumber” to the main method.

else

return MonthName.s[12];

This returned value is stored in a variable (str) and is later displayed on the console screen by making use of the System.out.println() method.

Here is the Java code:

Output: