Can you please help me fix my code I am still getting complie errors * use a swi
ID: 3883209 • Letter: C
Question
Can you please help me fix my code I am still getting complie errors * use a switch statement for this function (no ifs allowed)
+ * 1=January, 2=February ... 12=December (notice they start with uppercase)
+ * return "Invalid Month" if not between 1 and 12.
+ * @return
static String theMonth[] ={"","January","February","March","April","May" ,"June", "July", "August", "September", "October","November", "December"}; public static String monthName(int month)
{ String answer="Invalid Month";
switch(month)
{ case 1:
answer = theMonth[1];
break;
case 2:
answer = theMonth[2];
break;
case 3:
answer = theMonth[3];
break;
case 4:
answer = theMonth[4];
break;
case 5:
answer = theMonth[5];
break;
case 6:
answer = theMonth[6];
break;
case 7:
answer = theMonth[7];
break;
case 8:
answer = theMonth[8];
break;
case 9:
answer = theMonth[9];
break;
case 10:
answer = theMonth[10];
break;
case 11:
answer = theMonth[11];
break;
case 12:
answer = theMonth[12];
break;
default:
answer="Invalid Month";
}
return answer;
}
Explanation / Answer
Note: If u have further nay doubts just give me a comment.So that I will explain you clearly
__________________
Program.java
import java.util.Scanner;
public class Program {
// Declaring static array which holds month names
static String theMonth[] = {
"",
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
};
public static void main(String[] args) {
// Declaring variables
int month = 0;
/*
* Creating an Scanner class object which is used to get the inputs
* entered by the user
*/
Scanner sc = new Scanner(System.in);
// Getting the input entered by the user
System.out.print("Enter a Number :");
month = sc.nextInt();
// Calling the method by passing the user entered number
String monName = monthName(month);
// Displaying the output
System.out.println(monName);
}
public static String monthName(int month) {
String answer = "Invalid Month";
switch (month) {
case 1:
answer = theMonth[1];
break;
case 2:
answer = theMonth[2];
break;
case 3:
answer = theMonth[3];
break;
case 4:
answer = theMonth[4];
break;
case 5:
answer = theMonth[5];
break;
case 6:
answer = theMonth[6];
break;
case 7:
answer = theMonth[7];
break;
case 8:
answer = theMonth[8];
break;
case 9:
answer = theMonth[9];
break;
case 10:
answer = theMonth[10];
break;
case 11:
answer = theMonth[11];
break;
case 12:
answer = theMonth[12];
break;
default:
answer = "Invalid Month";
}
return answer;
}
}
__________________
Output:
Enter a Number :12
December
__________________
Output#1:
Enter a Number :7
July
____________Thank You