Search requires an index. Run npm run build once, then restart dev.
Loop Control
beginner40 min
Breaking Out of Loops
The break statement immediately exits the loop, moving execution to the first line after the loop block.
Using Break Statement:
// Counting from 1 to 5 with breakint number = 1;while (true) { System.out.println(number); if (number >= 5) { break; // Exit when we reach 5 } number = number + 1;}System.out.println("Ready!");// Output: 1, 2, 3, 4, 5, Ready!
Continue Statement
The continue statement skips the rest of the current loop iteration and jumps back to the beginning of the loop to check the condition again.
Using Continue Statement:
Scanner scanner = new Scanner(System.in);while (true) { System.out.println("Insert positive integers"); int number = Integer.valueOf(scanner.nextLine()); if (number <= 0) { System.out.println("Unfit number! Try again."); continue; // Skip to beginning of loop } if (number == 999) { break; // Exit condition } System.out.println("Your input was " + number);}// Robot example: Process valid sensor readings onlywhile (true) { System.out.println("Enter sensor reading (0-100, -1 to exit)"); int reading = Integer.valueOf(scanner.nextLine()); if (reading == -1) { break; } if (reading < 0 || reading > 100) { System.out.println("Invalid reading! Must be 0-100"); continue; // Skip invalid readings } System.out.println("Processing sensor reading: " + reading);}
Loop Execution Timing
Important: Loop conditions are only checked at the beginning of each iteration and when the loop first starts. Changes to variables inside the loop don’t immediately stop the loop.
Loop Timing Example:
int number = 1;while (number != 2) { System.out.println(number); // prints 1 number = 2; // Now number equals 2 System.out.println(number); // prints 2 number = 1; // Back to 1 - loop continues!}// This loop runs forever!// The condition (number != 2) is only checked:// 1. When loop starts// 2. After reaching the closing }// For loop example:for (int i = 0; i != 100; i++) { System.out.println(i); // prints current i i = 100; // Set i to 100 System.out.println(i); // prints 100 i = 0; // Reset i to 0} // At this point, i++ makes i = 1, loop continues// This loop also runs forever!
Loop Control Best Practices:
Important Guidelines:
Always update loop variables: Ensure conditions can eventually become false
Use break wisely: Provide clear exit conditions for infinite loops
Continue for validation: Skip invalid input without exiting the loop
Single clear task: Each if-statement should have one specific purpose
Try It Yourself:
Exercise 1: Loop Control Practice
Create a number validator that uses continue for invalid input
Build a menu system that uses break to exit
Make a sensor monitoring system with both break and continue
Create a robot safety system with emergency break conditions
Practice using break and continue statements:
Create a number validator that uses continue for invalid input
Create a number validator that uses continue for invalid input
import java.util.Scanner;
public class NumberValidator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int validNumbers = 0;
int invalidAttempts = 0;
double sum = 0.0;
final int TARGET_NUMBERS = 5;
System.out.println("=== Robot Sensor Value Validator ===");
System.out.println("Enter " + TARGET_NUMBERS + " valid sensor readings (0.0 - 100.0)");
System.out.println("Type 'quit' to exit early\n");
while (validNumbers < TARGET_NUMBERS) {
System.out.print("Sensor reading " + (validNumbers + 1) + "/" + TARGET_NUMBERS + ": ");
String input = scanner.nextLine().trim();
// Check for quit command
if (input.equalsIgnoreCase("quit")) {
System.out.println("Validation stopped by user.");
break;
}
// Try to parse the number
double reading;
try {
reading = Double.parseDouble(input);
} catch (NumberFormatException e) {
System.out.println("❌ Invalid format! Please enter a decimal number.");
invalidAttempts++;
continue; // Skip this iteration, try again
}
// Validate range
if (reading < 0.0 || reading > 100.0) {
System.out.println("❌ Out of range! Value must be between 0.0 and 100.0");
System.out.println(" Your input: " + reading);
invalidAttempts++;
continue; // Skip this iteration, try again
}
// Check for suspicious values
if (reading == 0.0 || reading == 100.0) {
System.out.print("⚠️ Extreme value detected (" + reading + "). Are you sure? (y/n): ");
String confirm = scanner.nextLine().trim().toLowerCase();
if (!confirm.equals("y") && !confirm.equals("yes")) {
System.out.println("Value rejected by user.");
invalidAttempts++;
continue; // Skip this iteration
}
}
// Value is valid!
validNumbers++;
sum += reading;
System.out.println("✅ Valid reading accepted: " + reading);
// Show progress
if (validNumbers < TARGET_NUMBERS) {
double currentAverage = sum / validNumbers;
System.out.println(" Current average: " + String.format("%.2f", currentAverage));
System.out.println(" Progress: " + validNumbers + "/" + TARGET_NUMBERS + " readings");
}
}
// Final results
System.out.println("\n=== Validation Complete ===");
System.out.println("Valid readings collected: " + validNumbers);
System.out.println("Invalid attempts: " + invalidAttempts);
if (validNumbers > 0) {
double average = sum / validNumbers;
System.out.println("Average sensor value: " + String.format("%.2f", average));
// Assess data quality
double errorRate = (double) invalidAttempts / (validNumbers + invalidAttempts) * 100;
System.out.println("Error rate: " + String.format("%.1f", errorRate) + "%");
if (errorRate < 10) {
System.out.println("✅ Excellent data quality");
} else if (errorRate < 25) {
System.out.println("⚠️ Acceptable data quality");
} else {
System.out.println("❌ Poor data quality - check input process");
}
}
System.out.println("Number validation complete.");
}
}
Build a menu system that uses break to exit
Build a menu system that uses break to exit
import java.util.Scanner;
public class RobotControlMenu {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean robotArmed = false;
int batteryLevel = 85;
String currentMode = "STOPPED";
int commandCount = 0;
System.out.println("=== FRC Robot Control System ===");
System.out.println("Robot initialized and ready for commands\n");
while (true) {
// Display current status
System.out.println("\n=== Robot Status ===");
System.out.println("Mode: " + currentMode);
System.out.println("Armed: " + (robotArmed ? "YES" : "NO"));
System.out.println("Battery: " + batteryLevel + "%");
System.out.println("Commands executed: " + commandCount);
// Display menu
System.out.println("\n=== Control Menu ===");
System.out.println("1. Arm/Disarm robot");
System.out.println("2. Start autonomous mode");
System.out.println("3. Start teleop mode");
System.out.println("4. Emergency stop");
System.out.println("5. Battery status");
System.out.println("6. System diagnostics");
System.out.println("0. Shutdown robot");
System.out.print("\nEnter command: ");
String input = scanner.nextLine().trim();
commandCount++;
// Process menu choice
if (input.equals("0")) {
System.out.println("\n🔴 SHUTDOWN SEQUENCE INITIATED");
System.out.print("Are you sure you want to shutdown? (y/n): ");
String confirm = scanner.nextLine().trim().toLowerCase();
if (confirm.equals("y") || confirm.equals("yes")) {
System.out.println("\n🤖 Shutting down robot systems...");
System.out.println(" → Stopping all motors");
System.out.println(" → Disabling sensors");
System.out.println(" → Saving configuration");
System.out.println(" → Robot shutdown complete");
break; // Exit the main loop
} else {
System.out.println("Shutdown cancelled.");
}
} else if (input.equals("1")) {
robotArmed = !robotArmed;
System.out.println("🔧 Robot " + (robotArmed ? "ARMED" : "DISARMED"));
if (robotArmed) {
System.out.println(" ⚠️ Robot is now ready for operation");
System.out.println(" ⚠️ Use caution when executing commands");
} else {
currentMode = "STOPPED";
System.out.println(" ✅ Robot is now safe");
}
} else if (input.equals("2")) {
if (!robotArmed) {
System.out.println("❌ Cannot start autonomous - robot not armed");
} else if (batteryLevel < 20) {
System.out.println("❌ Cannot start autonomous - low battery");
} else {
currentMode = "AUTONOMOUS";
System.out.println("🤖 Autonomous mode started");
System.out.println(" → Robot executing pre-programmed sequence");
batteryLevel -= 5; // Simulate battery usage
}
} else if (input.equals("3")) {
if (!robotArmed) {
System.out.println("❌ Cannot start teleop - robot not armed");
} else {
currentMode = "TELEOP";
System.out.println("🎮 Teleop mode started");
System.out.println(" → Robot ready for manual control");
batteryLevel -= 2; // Simulate battery usage
}
} else if (input.equals("4")) {
currentMode = "EMERGENCY_STOP";
robotArmed = false;
System.out.println("🚨 EMERGENCY STOP ACTIVATED");
System.out.println(" → All motors stopped immediately");
System.out.println(" → Robot automatically disarmed");
System.out.println(" → Check robot before re-arming");
} else if (input.equals("5")) {
System.out.println("🔋 Battery Status Report:");
System.out.println(" Current level: " + batteryLevel + "%");
if (batteryLevel > 80) {
System.out.println(" Status: ✅ Excellent");
} else if (batteryLevel > 50) {
System.out.println(" Status: ⚠️ Good");
} else if (batteryLevel > 20) {
System.out.println(" Status: ⚠️ Low - consider charging");
} else {
System.out.println(" Status: 🔴 Critical - charge immediately");
}
int estimatedRuntime = batteryLevel / 5; // Rough estimate
System.out.println(" Estimated runtime: " + estimatedRuntime + " minutes");
} else if (input.equals("6")) {
System.out.println("🔍 System Diagnostics:");
System.out.println(" Motors: ✅ All operational");
System.out.println(" Sensors: ✅ All responding");
System.out.println(" Communication: ✅ Strong signal");
System.out.println(" Temperature: ✅ Normal (" + (int)(Math.random() * 10 + 65) + "°F)");
System.out.println(" Voltage: ✅ Stable (" + String.format("%.1f", 11.5 + Math.random()) + "V)");
} else {
System.out.println("❌ Invalid command: " + input);
System.out.println(" Please enter a number 0-6");
commandCount--; // Don't count invalid commands
}
// Simulate battery drain over time
if (commandCount % 3 == 0 && batteryLevel > 0) {
batteryLevel = Math.max(0, batteryLevel - 1);
}
// Critical battery warning
if (batteryLevel <= 15 && robotArmed) {
System.out.println("\n⚠️ WARNING: Critical battery level!");
System.out.println(" Consider shutdown to prevent damage");
}
// Auto-shutdown on dead battery
if (batteryLevel <= 0) {
System.out.println("\n🔴 CRITICAL: Battery depleted!");
System.out.println("🤖 Initiating emergency shutdown...");
break; // Emergency exit
}
}
// Cleanup and final status
System.out.println("\n=== Final Status Report ===");
System.out.println("Final mode: " + currentMode);
System.out.println("Final battery: " + batteryLevel + "%");
System.out.println("Commands processed: " + commandCount);
System.out.println("\nRobot control system terminated.");
System.out.println("Thank you for using FRC Robot Control!");
}
}