The switch
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:
import java.util.Scanner; public class Days { public static void main(String[] args) {
Next, declare a Scanner variable and create the object. This object will retrieve user input later:
Scanner in = new Scanner(System.in);
Declare a variable to store the user input:
int dayNum;
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 a switch
statement that switches on the dayNum variable:
switch(dayNum) {
Inside the switch
statement, add cases for each day. For example, the value 1
will output Monday:
case 1: System.out.println("Monday"); break;
Here are the other cases. Note that case 5
also outputs TGIF:
case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; case 4: System.out.println("Thursday"); break; case 5: System.out.println("Friday"); System.out.println("TGIF!"); break; case 6: System.out.println("Saturday"); break; case 7: 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 the switch
statement, main method, and class:
} } }
Here is the complete program:
import java.util.Scanner; public class Days { public static void main(String[] args) { Scanner in = new Scanner(System.in); int dayNum; System.out.print("Enter a day number (1-7): "); dayNum = in.nextInt(); switch(dayNum) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; case 4: System.out.println("Thursday"); break; case 5: System.out.println("Friday"); System.out.println("TGIF!"); break; case 6: System.out.println("Saturday"); break; case 7: 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)