Java assignment 10: Select the month of the year

  Quizzes     Assignments     Puzzles     Easy exercises     Required knowledge  
Java Assignments   Green = Easy,  Blue = Normal,  Red = Hard
Select    01   02   03   04   05   06   07   08   09   10   By title 

Write a simple program that allows users to enter a number. For each number the program writes its equivalent month. If the user enters the number 5 for example, the program writes the equivalent month of 5, which is “May”.
That applies to all the months of the year. If the user enters an invalid number your program should write that there is no month belongs to that number, as shown below.

When you run the program the following will happen:

1. The program asks the user to insert a number and press the enter button.
2. The program writes the month which belongs to that number.

Answer explanation

You can write the program using the switch statemen. By each case assign the value of the month to the number as shown below.

Java assignment 10: Select the month of the year

Level: Normal

import java.util.Scanner;

public class Month
{
  public String getMonth(int monthNr)
  {
    String monthName = "";
    switch(monthNr)
    {
      case 1:
        monthName = "January.";
        break;
      case 2:
        monthName = "February";
        break;
      case 3:
        monthName = "March";
        break;
      case 4:
        monthName = "April";
        break;
      case 5:
        monthName = "May";
        break;
      case 6:
        monthName = "June";
        break;
      case 7:
        monthName = "July";
        break;
      case 8:
        monthName = "August";
        break;
      case 9:
        monthName = "September";
        break;
      case 10:
        monthName = "October";
        break;
      case 11:
        monthName = "November";
        break;
      case 12:
        monthName = "December";
        break;
      default:
        monthName = "Not valid.";
    }
    return monthName;
  }
  public static void main(String[] args)
  {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter a number: ");
    int monthNr = input.nextInt();
    Month monthObject = new Month();
    System.out.print(monthNr + " is " +
        monthObject.getMonth(monthNr));
    input.close();
  }
}
Author: Sar Maroof



Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.
 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

Leave a Reply

Your email address will not be published. Required fields are marked *