Computer Science, asked by Anonymous, 6 months ago

Write code segments in Java to input integer value of a month and output the month name. For example, if the input is 3 then the output will be "March", and if the input is 12 then the output will be “December”.

Answers

Answered by Oreki
3

Array Implementation:

import java.util.Scanner;  

public class Months {

   public static void main(String[ ] args) {

       String[ ] months = {"None", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};

       System.out.print("Enter number - ");

       int monthNo = new Scanner(System.in).nextInt( );

       System.out.println(monthNo > months.length ? "None" : months[monthNo]);

   }

}

Switch Implementation:

import java.util.Scanner;

public class Months_2 {

   public static void main(String[] args) {

       System.out.print("Enter number - ");

       int monthNo = new Scanner(System.in).nextInt();

       String month = "";

       switch (monthNo) {

           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 = "None";

       }

       System.out.println(month);

   }

}

Similar questions