Lucky Cat Tutoring Services

CS111 Decision Structures part 1
September 17, 2009, 3:20 pm
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(;

// 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.
switch (number)
case 1:
System.out.println(“You entered 1.”);
case 2:
System.out.println(“You entered 2.”);
case 3:
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

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: