Please explain/comment this code import java.util.*; public class month { int mo
ID: 3862232 • Letter: P
Question
Please explain/comment this code
import java.util.*;
public class month {
int monthinput()
{
Scanner s=new Scanner(System.in);
return(s.nextInt());
}
String monthname(int n)
{
String a;
if(n==1)
{
return ("january");
}
if(n==2)
{
return("febrauary");
}
if(n==3)
{
return("march");
}
if(n==4)
{
return("april");
}
if(n==5)
{
return("may");
}
if(n==6)
{
return("june");
}
if(n==7)
{
return("july");
}
if(n==8)
{
return("august");
}
if(n==9)
{
return("september");
}
if(n==10)
{
return("october");
}
if(n==11)
{
return("november");
}
if(n==12)
{
return("december");
}
return null;
}
void displaymonth(String ss)
{
System.out.println("the given month is"+" "+ss);
}
}
driver programme is
public class driver {
public static void main(String args[])
{
month m=new month();
int x=m.monthinput();
String s=m.monthname(x);
m.displaymonth(s);
}
}
Explanation / Answer
Explanation:
This program is for printing the month name if the month number is given.
Added Comments to the above code :
import java.util.*; //Importing util packages to use classes like Scanner etc.,
public class month {
// This method is used for reading the input month from the user
int monthinput()
{
/*Scanner class is building class used for reading input from user. It always reads input as String so need to convert into integer using nextInt() method */
Scanner s=new Scanner(System.in);
return(s.nextInt()); //returns month number entered to driver class
}
// method for returning month name based on month value provided.
String monthname(int n)
{
String a;
if(n==1) /*verifies if month value provided is 1 or not. If month value is 1 then month name is returned as “January”*/
{
return ("january");
}
if(n==2)
{
return("febrauary");
}
if(n==3)
{
return("march");
}
if(n==4)
{
return("april");
}
if(n==5)
{
return("may");
}
if(n==6)
{
return("june");
}
if(n==7)
{
return("july");
}
if(n==8)
{
return("august");
}
if(n==9)
{
return("september");
}
if(n==10)
{
return("october");
}
if(n==11)
{
return("november");
}
if(n==12)
{
return("december");
}
return null;
}
//this method displays the month name for month number entered by user
void displaymonth(String ss)
{
System.out.println("the given month is"+" "+ss);
}
}
driver programme is
/* your code starts with this class as it is having main class*/
public class driver {
public static void main(String args[])
{
month m=new month(); //creating object for month class
/*invoking monthinput method which returns the month value in integer data type*/
int x=m.monthinput();
/*invoking monthname method which returns the month name in string data type*/
String s=m.monthname(x);
/*invoking displaymonth method which prints month name entered by user*/
m.displaymonth(s);
}
}