Java Control Structures: Switch Statements, While Loops, and Variable Scope
Switch Statements
Purpose
Primarily used for equality comparisons against multiple values.
Syntax
switch(variable) {
case value1:
// code block
break;
case value2:
// code block
break;
default:
// default code block
break;
}
Key notes:
- Default block is optional
- Break statemants exit the switch block
- Supported variable types: integers, characters, strings (JDK 1.6+)
- Multiple cases can be combined
Example:
int rank = input.nextInt();
switch(rank) {
case 1:
System.out.println("Trip");
break;
case 2:
System.out.println("Laptop");
break;
case 3:
System.out.println("Hard drive");
break;
default:
System.out.println("Nothing");
break;
}
While Loops
Purpose
Execute code blocks repeatedly while a condition remains true.
Basic Structure
while(condition) {
// loop body
}
Fixed-count example:
int counter = 1;
while(counter <= 5) {
System.out.println("Iteration: " + counter);
counter++;
}
Summing numbers 1-100:
int total = 0;
int num = 1;
while(num <= 100) {
total += num;
num++;
}
System.out.println("Sum: " + total);
User-controlled loop:
String response = "y";
while(response.equals("y")) {
System.out.println("Running lap...");
response = input.next();
}
Variable Scope
- Local variables: Dcelared within braces, only accessible within those braces
- Global variables: Declared outside braces, accessible throughout the containing scope
Practice Exercises
- Print numbers from 100 to 5 in decrements of 5:
int value = 100;
while(value >= 5) {
if(value % 5 == 0) {
System.out.print(value + " ");
}
value--;
}
- Sum numbers divisible by 7 between 1-50:
int sum = 0;
int current = 1;
while(current <= 50) {
if(current % 7 == 0) {
sum += current;
}
current++;
}
System.out.println("Sum: " + sum);
- Count numbers divisible by both 3 and 5 between 1-100:
int count = 0;
int number = 1;
while(number <= 100) {
if(number % 3 == 0 && number % 5 == 0) {
count++;
}
number++;
}
System.out.println("Count: " + count);
- Weekly schedule using switch:
switch(day) {
case 1: case 3: case 5:
System.out.println("Programming");
break;
case 2: case 4: case 6:
System.out.println("English");
break;
case 7:
System.out.println("Rest day");
break;
}
- Shopping cart calculator:
int price, total = 0, items = 0;
price = input.nextInt();
while(price != 0) {
total += price;
items++;
price = input.nextInt();
}
System.out.println(items + " items, total: " + total);