Question: write a program that randomly generates an integer between 1 and 12 and displays the English month names January,
February,..., December for the number 1, 2, ... 12 using switch-case statement. Print out the random number and the English name.
Hint 1: Generate random number
If you want to generate a number from 0 to 100 then your code would look like this:
(int)(Math.random() * 101);
To generate a number from 10 to 20:
(int)(Math.random() * 11 + 10);
In the general case:
(int)(Math.random() * ((upperbound - lowerbound) + 1) + lowerbound);
(where lowerbound is inclusive and upperbound exclusive).
Hint 2: Switch-case statement
The syntax of a switch case statement is the following:
switch (variable) {
case c1:
statements // they are executed if variable == c1
break;
case c2:
statements // they are executed if variable == c2
break;
case c3:
case c4:
statements // they are executed if variable == any of the above c's
break;
. . .
default:
statements // they are executed if none of the above case is satisfied
break;
}
Sample Run:
The random number is: 5
It is May.
What I have tried:
This is what I have done but the sample run does not come out the same.
The sample run would put out the month instead of Sample Run:
The random number is: 5
It is May.
public class Practiceofmn {
public static void main(String[] args) {
int month = (int)((Math.random() * 12) + 1);
switch (month)
{
case 1: System.out.println("January"); break;
case 2: System.out.println("February"); break;
case 3: System.out.println("March"); break;
case 4: System.out.println("April"); break;
case 5: System.out.println("May"); break;
case 6: System.out.println("June"); break;
case 7: System.out.println("July"); break;
case 8: System.out.println("August"); break;
case 9: System.out.println("September"); break;
case 10: System.out.println("October"); break;
case 11: System.out.println("November"); break;
case 12: System.out.println("December");
}
}
}