Filed under: Uncategorized
Even the most basic programs have to make choices. We do this with “if-then”, “if-else”, “if-else-if”, “Switch” and other decision structures.
Switch Control Structure: acts like an if else statment; lets user pick an option and ‘switches’
Start with SWITCH which is a keyword and tells the program to evaluate that variable (in example is “number”). Switch can only compare INT or CHAR variables. BREAK after each case pops out of the control structure.
import java.util.Scanner; // Needed for Scanner class
This program demonstrates the switch statement.
public class SwitchDemo
public static void main(String args)
int number; // A number entered by the user
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Get one of the numbers 1, 2, or 3 from the user.
System.out.print(“Enter 1, 2, or 3: “);
number = keyboard.nextInt();
// Determine the number entered.
System.out.println(“You entered 1.”);
System.out.println(“You entered 2.”);
System.out.println(“You entered 3.”);
System.out.println(“That’s not 1, 2, or 3!”);
Switch control structures are easier to read than other forms
Leave a Comment so far
Leave a comment