How to Represent a Month Value from Numbers in Java

Problem:

Write a program that would read an input from the user that represents the month value. Then the code will display the name of the month based on this value, using the switch statement. For example, if the user input is:

Output:

Please enter the month number:
4

The month selected is: APRIL

Solution:

import java.util.Scanner;

public class Problem2 {
     public static void main(String[] args) {
           Scanner input = new Scanner(System.in);
           System.out.println( "Please enter the number of the month:");
           int monthvalue = input.nextInt();
           String month;
           switch(monthvalue){
               case 1: month = "January";
                   break;
               case 2: month = "February";
                   break;
               case 3: month = "March";
                   break;
               case 4: month = "April";
                   break;
               case 5: month = "May";
                   break;
               case 6: month = "June";
                   break;
               case 7: month = "July";
                   break;
               case 8: month = "August";
                   break;
               case 9: month = "September";
                   break;
               case 10: month = "October";
                   break;
               case 11: month = "November";
                   break;
               case 12: month = "December";
                   break;
               default: month = "Invalid Month";
                   break;
           }
         
           System.out.println(month);
     }
}


No comments :

Post a Comment

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact