Back

Activity 2.10 More Control Flow

divider

Introduction

Activity 2.10

More Control Flow

Topics

  • break and continue Keywords
  • Ternary Operator
  • switch Statement
  • do-while Loop
  • Short-Circuit Evaluation
  • DeMorgan's Theorem

break Statement

Immediately exits the nearest enclosing loop.

for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // exits the loop entirely
}
System.out.println(i);
}
System.out.println("Loop ended");
1
2
3
4
Loop ended

continue Statement

Skips the rest of the current iteration and moves to the next one.

for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // skip even numbers
}
System.out.println(i);
}
1
3
5
7
9

Ternary Operator

A compact conditional operator (?:) that returns one of two values based on whether a condition is true or false.

It provides a compact way to choose between two values.

Syntax: condition ? valueIfTrue : valueIfFalse;

int number = 7;
String result = (number % 2 == 0) ? "Even" : "Odd";
System.out.println(result);
Odd

switch Statement

A control structure that selectes and executes one block of code from multiple options based on the value of an expression.

It can be used to simplify some if/else if/else statements.

String grade = "A";
if (grade.equals("A"))
System.out.println("Excellent!");
else if (grade.equals("B"))
System.out.println("Good job!");
else if (grade.equals("C"))
System.out.println("Not bad.");
else
System.out.println("Needs improvement.");

switch Statement

A control structure that selectes and executes one block of code from multiple options based on the value of an expression.

It can be used to simplify some if/else if/else statements.

String grade = "A";
switch (grade)
{
case "A" -> System.out.println("Excellent!");
case "B" -> System.out.println("Good job!");
case "C" -> System.out.println("Not bad.");
default -> System.out.println("Needs improvement.");
}

do-while Loop

A control structure that executes its body at least once and then repeats as long as a specified condition remains true.

Scanner input = new Scanner(System.in);
int number;
do {
System.out.print("Enter a positive number: ");
number = input.nextInt();
} while (number <= 0);

Short-Circuit Evaluation

A behavior where Java stops evaluating a logical expression as soon as the result is known.

  • && (AND): If the left side is false, Java does not check the right side.
  • || (OR): If the left side is true, Java does not check the right side.

DeMorgan's Theorem

De Morgan's laws let us rewrite logical expressions involving !, &&, and ||.

!(x > 0 && y > 0) is the same as x <= 0 || y <= 0.

!(isRaining || isSnowing) is the same as !isRaining && !isSnowing.

Challenge: Simplify !(a < 5 || b >= 10)

Answer: a >= 5 && b < 10

Key Terms

break Keyword
Ends the nearest enclosing loop or switch statement immediately, skipping any remaining code inside it.
continue Keyword
Skips the rest of the current loop iteration and jumps to the next iteration of the loop.
Ternary Operator
A compact conditional operator that returns one of two values based on whether a condition is true or false.

Key Terms

switch Statement
A control structure that chooses one block of code to execute from multiple possible cases based on the value of an expression.
do-while Loop
A control structure that runs its body at least once and continues repeating while a condition remains true.

Key Terms

Short-Circuit Evaluation
A behavior where Java stops evaluating a logical expression as soon as the result is known.
DeMorgan's Theorem
A rule for simplifying negated boolean expressions.

'F' → Fullscreen

Objectives

  • icon Practice various control flow constructs and techniques
divider

Activity Tasks

  • icon Create a new project named 2-10-More-Control-Flow.
  • icon Complete each task individually.

Task 1: Prime Number Calculator

  • icon A prime number is a whole number greater than 1 that has exactly two distinct positive factors: 1 and itself.
Program.java
import java.util.Scanner;
public class Program
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("\n--- Demo 1: Prime Number Checker ---");
System.out.print("Enter an integer: ");
int number = input.nextInt();
boolean isPrime = true;
for (int i = 2; i < number; i++)
{
if (number % i == 0)
{
isPrime = false;
break;
}
}
System.out.println(number + " is " + (isPrime ? "prime" : "not prime"));
input.nextLine(); // Consume newline
System.out.print("Press enter to continue...");
input.nextLine();
// -----------------------------------------------------------------------------
}
}
//

Task 2: Day of the Week

Program.java
import java.util.Scanner;
public class Program
{
public static void main(String[] args)
{
22 collapsed lines
Scanner input = new Scanner(System.in);
System.out.println("\n--- Demo 1: Prime Number Checker ---");
System.out.print("Enter an integer: ");
int number = input.nextInt();
boolean isPrime = true;
for (int i = 2; i < number; i++)
{
if (number % i == 0)
{
isPrime = false;
break;
}
}
System.out.println(number + " is " + (isPrime ? "prime" : "not prime"));
input.nextLine(); // Consume newline
System.out.print("Press enter to continue...");
input.nextLine();
// -----------------------------------------------------------------------------
System.out.println("\n--- Demo 2: Day of the Week ---");
System.out.print("Enter a number between 1 and 7: ");
int day = input.nextInt();
switch (day)
{
case 1 -> System.out.println("Monday");
case 2 -> System.out.println("Tuesday");
case 3 -> System.out.println("Wednesday");
case 4 -> System.out.println("Thursday");
case 5 -> System.out.println("Friday");
case 6 -> System.out.println("Saturday");
case 7 -> System.out.println("Sunday");
default -> System.out.println("Invalid day");
}
input.nextLine(); // Consume newline
System.out.print("Press enter to continue...");
input.nextLine();
// -----------------------------------------------------------------------------
}
}
//

Task 3: Number Analyzer

Program.java
import java.util.Scanner;
public class Program
{
public static void main(String[] args)
{
44 collapsed lines
Scanner input = new Scanner(System.in);
System.out.println("\n--- Demo 1: Prime Number Checker ---");
System.out.print("Enter an integer: ");
int number = input.nextInt();
boolean isPrime = true;
for (int i = 2; i < number; i++)
{
if (number % i == 0)
{
isPrime = false;
break;
}
}
System.out.println(number + " is " + (isPrime ? "prime" : "not prime"));
input.nextLine(); // Consume newline
System.out.print("Press enter to continue...");
input.nextLine();
// -----------------------------------------------------------------------------
System.out.println("\n--- Demo 2: Day of the Week ---");
System.out.print("Enter a number between 1 and 7: ");
int day = input.nextInt();
switch (day)
{
case 1 -> System.out.println("Monday");
case 2 -> System.out.println("Tuesday");
case 3 -> System.out.println("Wednesday");
case 4 -> System.out.println("Thursday");
case 5 -> System.out.println("Friday");
case 6 -> System.out.println("Saturday");
case 7 -> System.out.println("Sunday");
default -> System.out.println("Invalid day");
}
input.nextLine(); // Consume newline
System.out.print("Press enter to continue...");
input.nextLine();
// -----------------------------------------------------------------------------
System.out.println("\n--- Demo 3: Number Analyzer ---");
for (int i = 0; i < 5; i++)
{
System.out.print("Enter a number: ");
int n = input.nextInt();
if (n == 0)
{
System.out.println("Skipping zero...");
continue;
}
String sign = (n > 0) ? "positive" : "negative";
String parity = (n % 2 == 0) ? "even" : "odd";
System.out.println(n + " is " + sign + " and " + parity + ".");
}
}
}
//
divider

Sample Output

Your program output should something similar to the sample output below.

Sample Output
--- Demo 1: Prime Number Checker ---
Enter an integer: 5
5 is prime
Press enter to continue...
--- Demo 2: Day of the Week ---
Enter a number between 1 and 7: 4
Thursday
Press enter to continue...
--- Demo 3: Number Analyzer ---
Enter a number: 3
3 is positive and odd.
Enter a number: 4
4 is positive and even.
Enter a number: 5
5 is positive and odd.
Enter a number: 6
6 is positive and even.
Enter a number: 7
7 is positive and odd.
divider

Reflection Questions

You may write your reflection answers as comments at the bottom of your code.

  1. How is continue different from break?
  2. Why can a switch statement sometimes be preferable to using if/else if/else statements?
divider

Submission

Submit your activity and reflection answers to the appropriate dropbox.

Activity Complete