Java provides a powerful tool known as the “switch” statement, which allows developers to easily control the flow of their programs based on a specific value or variable. In this blog post, we will take a look at how to use switch statements in Java, including an example program to help illustrate the concept.
First, let’s start with the basic structure of a switch statement. The switch statement is used to compare a variable or value against a series of “case” statements. Each case statement is associated with a specific value or range of values, and the program will execute the code associated with the first case statement that matches the variable or value being tested.
Here is an example of a simple switch statement:
int myValue = 3;
switch (myValue) {
case 1:
System.out.println("The value is 1");
break;
case 2:
System.out.println("The value is 2");
break;
case 3:
System.out.println("The value is 3");
break;
default:
System.out.println("The value is not 1, 2, or 3");
break;
}
In this example, the variable “myValue” is set to 3. The switch statement compares this value against each of the case statements, and when it finds a match (in this case, case 3), it executes the code associated with that case statement (in this case, “The value is 3”).
It’s important to note that the “break” statement is used to end the switch statement and exit the block of code associated with each case statement. If you don’t include a break statement, the program will continue to execute the code for all of the case statements that come after the matching case statement.
Flow chart of the switch statement
Now let’s look at a more complex example program that uses a switch statement to control the flow of a simple menu-based program.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int menuOption;
boolean validOption = false;
while (!validOption) {
System.out.println("Please choose a menu option:");
System.out.println("1. Option 1");
System.out.println("2. Option 2");
System.out.println("3. Option 3");
System.out.println("4. Exit");
menuOption = input.nextInt();
switch (menuOption) {
case 1:
System.out.println("You have selected Option 1.");
validOption = true;
break;
case 2:
System.out.println("You have selected Option 2.");
validOption = true;
break;
case 3:
System.out.println("You have selected Option 3.");
validOption = true;
break;
case 4:
System.out.println("Exiting program.");
validOption = true;
break;
default:
System.out.println("Invalid option. Please try again.");
break;
}
}
}
}
- The program imports the Scanner class from java.util package in order to allow user input.
- A variable named “menuOption” is declared as an integer and a variable named “validOption” is declared as a boolean and initialized as false.
- A while loop is created that continues to run as long as the “validOption” variable is false.
- Within the while loop, the program prompts the user to choose a menu option with a list of options (1. Option 1, 2. Option 2, 3. Option 3, 4. Exit).
- The user’s input is saved as the “menuOption” variable.
- A switch statement is used to check the value of the “menuOption” variable and corresponding actions are taken based on the user’s input.
- If the user input is 1, the program prints “You have selected Option 1.” and sets the “validOption” variable to true, breaking the loop.
- If the user input is 2, the program prints “You have selected Option 2.” and sets the “validOption” variable to true, breaking the loop.
- If the user input is 3, the program prints “You have selected Option 3.” and sets the “validOption” variable to true, breaking the loop.
- If the user input is 4, the program prints “Exiting program.” and sets the “validOption” variable to true, breaking the loop.
- If the user input is anything other than 1, 2, 3, or 4, the program prints “Invalid option. Please try again.” and the loop continues.
- The program exits once a valid menu option has been selected.
Latest Posts:
- Merging Two Sorted Arrays in JavaTitle: Merging Two Sorted Arrays in Java Merging two sorted arrays into a single array is a common operation in… Read more: Merging Two Sorted Arrays in Java
- Frequency of Elements in an ArrayTitle: Frequency of Elements in an Array Using Java Counting the frequency of elements in an array is a fundamental… Read more: Frequency of Elements in an Array
- Calculate the sum of diagonals in a matrixTitle: Calculate the sum of diagonals in a matrix In this blog post, we’ll delve into the world of matrices… Read more: Calculate the sum of diagonals in a matrix
- Binary Search in JavaBinary search is a powerful algorithm used to efficiently find a target value in a sorted array. In this blog… Read more: Binary Search in Java
- Removing Duplicate Elements in Array using JavaRemoving Duplicate Elements in Array using Java Arrays are fundamental in Java, but duplicate elements can clutter your data. In… Read more: Removing Duplicate Elements in Array using Java
- Transpose a 2D Array in JavaTitle: Transpose a 2D Array in Java In Java, transposing a 2D array involves converting its rows into columns and… Read more: Transpose a 2D Array in Java