Theswitch
statement is a useful selection statement when there are many values that require different logic.
Here is a program that asks the user to enter a day number (1-7) and outputs the full name of that day of the week.
First, import the Scanner class (for user input), declare the class name, and declare the main method:
importjava.util.Scanner;publicclassDays{publicstaticvoidmain(String[]args){
Next, declare a Scanner variable and create the object. This object will retrieve user input later:
Scannerin=newScanner(System.in);
Declare a variable to store the user input:
intdayNum;
Ask the user to enter a number:
System.out.print("Enter a day number (1-7): ");
Use the Scanner object to retrieve the user input. Note that the program will wait here until the user types a value and presses Enter:
dayNum=in.nextInt();
Create aswitch
statement that switches on the dayNum variable:
switch(dayNum){
Inside theswitch
statement, add cases for each day. For example, the value1
will output Monday:
case1:System.out.println("Monday");break;
Here are the other cases. Note that case5
also outputs TGIF:
case2:System.out.println("Tuesday");break;case3:System.out.println("Wednesday");break;case4:System.out.println("Thursday");break;case5:System.out.println("Friday");System.out.println("TGIF!");break;case6:System.out.println("Saturday");break;case7:System.out.println("Sunday");break;
The last case is a default case. This case occurs when the dayNum value has a number outside the range 1-7:
default:System.out.println("Invalid day number.");break;
Finally, add the closing curly brackets for theswitch
statement, main method, and class:
}}}
Here is the complete program:
importjava.util.Scanner;publicclassDays{publicstaticvoidmain(String[]args){Scannerin=newScanner(System.in);intdayNum;System.out.print("Enter a day number (1-7): ");dayNum=in.nextInt();switch(dayNum){case1:System.out.println("Monday");break;case2:System.out.println("Tuesday");break;case3:System.out.println("Wednesday");break;case4:System.out.println("Thursday");break;case5:System.out.println("Friday");System.out.println("TGIF!");break;case6:System.out.println("Saturday");break;case7:System.out.println("Sunday");break;default:System.out.println("Invalid day number.");break;}}}
Thanks for reading. 😃
Follow me on Twitter@realEdwinTorres
for more programming tips and help.
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse