Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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.
Java
public class Practiceofmn {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// Generate an integer between 1 and 12.
				int month = (int)((Math.random() * 12) + 1);

				// Display the English month name
				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");
				}
			}
		}
Posted
Updated 9-Feb-22 1:58am
v2
Comments
_Asif_ 9-Feb-22 8:36am    
Have you understood the Question completely?
Richard MacCutchan 9-Feb-22 8:53am    
The code works correctly.

1 solution

Are you really asking how to print the value of the random generated number?
If the answer is yes, then you either
  • copied from the interned the posted code.
or
  • copied the posted code from the internet.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900