Search requires an index. Run npm run build once, then restart dev.
While Loops
beginner65 min
Why Use Loops?
Loops allow programs to repeat code efficiently. Instead of writing the same code multiple times, loops execute a block of code repeatedly based on a condition.
Problem: Repetitive Code
// Without loops - inefficient and inflexibleScanner scanner = new Scanner(System.in);int sum = 0;System.out.println("Input a number: ");sum = sum + Integer.valueOf(scanner.nextLine());System.out.println("Input a number: ");sum = sum + Integer.valueOf(scanner.nextLine());System.out.println("Input a number: ");sum = sum + Integer.valueOf(scanner.nextLine());// What if we need 100 numbers? 1000 numbers?System.out.println("The sum is " + sum);
Solution: Using While Loops
// With loops - efficient and flexibleScanner scanner = new Scanner(System.in);int numbersRead = 0;int sum = 0;while (true) { if (numbersRead == 5) { break; // Exit when we've read 5 numbers } System.out.println("Input number"); sum = sum + Integer.valueOf(scanner.nextLine()); numbersRead = numbersRead + 1;}System.out.println("The sum of the numbers is " + sum);
Basic While Loop Structure:
while (condition) { // Code to repeat // This block executes while condition is true}// Simple counting exampleint count = 1;while (count <= 5) { System.out.println("Count: " + count); count = count + 1; // Important: update the condition!}
While Loop Syntax:
while (condition) { // Code to repeat // This block executes while condition is true}// Simple counting exampleint count = 1;while (count <= 5) { System.out.println("Count: " + count); count = count + 1; // Important: update the condition!}
Infinite Loops
Using while (true) creates an infinite loop that runs forever unless explicitly stopped with a break statement. This is useful for user input scenarios.
Infinite Loop Examples:
// This runs forever (until break is encountered)while (true) { System.out.println("I can program!");}// Practical infinite loop with break conditionint robotSpeed = 0;while (true) { robotSpeed += 10; System.out.println("Robot speed: " + robotSpeed); if (robotSpeed >= 100) { System.out.println("Maximum speed reached!"); break; // Exit the loop }}
User Input with While Loops:
Scanner scanner = new Scanner(System.in);// Keep asking until user wants to exitwhile (true) { System.out.println("Exit? (y exits)"); String input = scanner.nextLine(); if (input.equals("y")) { break; // Exit if user enters 'y' } System.out.println("Ok! Let's carry on!");}System.out.println("Ready!");// Robot example: Read sensor values until thresholdwhile (true) { System.out.println("Input sensor reading (0 to quit)"); int reading = Integer.valueOf(scanner.nextLine()); if (reading == 0) { break; } System.out.println("Sensor value: " + reading);}
While Loops with Conditions
Instead of using while (true) with break, you can put the condition directly in the while statement. This is more elegant when you know the exact condition to check.
Conditional While Loop:
// Count from 1 to 5 using conditionint number = 1;while (number < 6) { System.out.println(number); number++; // Shorthand for number = number + 1}// Robot example: Drive until target reacheddouble distanceToTarget = 100.0;double speed = 10.0;while (distanceToTarget > 0) { System.out.println("Distance remaining: " + distanceToTarget + " cm"); distanceToTarget -= speed; // Move closer to target // Slow down as we approach if (distanceToTarget < 20) { speed = 5.0; }}System.out.println("Target reached!");
Try It Yourself:
Exercise 1: While Loop Practice
Create a simple counting loop that prints numbers 1 to 10
Build a robot battery monitor using while(true) and break
Make a number guessing game with user input validation
Create a sensor reading loop that stops when target value is reached
Practice creating different types of while loops:
Create a simple counting loop that prints numbers 1 to 10
Create a simple counting loop that prints numbers 1 to 10
public class CountingLoop {
public static void main(String[] args) {
// Method 1: Using while with condition
System.out.println("=== Counting 1 to 10 (Conditional While) ===");
int count = 1;
while (count <= 10) {
System.out.println("Count: " + count);
count++;
}
System.out.println("Counting complete!");
// Method 2: Using while(true) with break
System.out.println("\n=== Counting 1 to 10 (Infinite While + Break) ===");
int num = 1;
while (true) {
System.out.println("Number: " + num);
if (num >= 10) {
break;
}
num++;
}
System.out.println("Break counting complete!");
// Robot example: Motor speed ramp
System.out.println("\n=== Robot Motor Speed Ramp ===");
int motorSpeed = 0;
while (motorSpeed < 100) {
System.out.println("Motor speed: " + motorSpeed + "%");
motorSpeed += 10; // Increase by 10% each step
// Simulate delay
try {
Thread.sleep(200);
} catch (InterruptedException e) {
break;
}
}
System.out.println("Motor at full speed: " + motorSpeed + "%");
}
}
Build a robot battery monitor using while(true) and break
Build a robot battery monitor using while(true) and break
import java.util.Scanner;
public class BatteryMonitor {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double currentVoltage = 12.6; // Starting voltage
int readingCount = 0;
double totalVoltage = 0.0;
int lowBatteryWarnings = 0;
System.out.println("=== Robot Battery Monitor ===");
System.out.println("Commands: 'reading' to simulate reading, 'exit' to quit");
System.out.println("Current battery: " + currentVoltage + "V");
while (true) {
System.out.print("\nBattery Monitor> ");
String command = scanner.nextLine().trim().toLowerCase();
// Exit condition
if (command.equals("exit") || command.equals("quit")) {
System.out.println("Battery monitoring stopped.");
break;
}
// Simulate battery reading
if (command.equals("reading")) {
// Simulate voltage drop over time
currentVoltage -= (Math.random() * 0.1 + 0.05);
readingCount++;
totalVoltage += currentVoltage;
System.out.println("📊 Battery Reading #" + readingCount);
System.out.println("Voltage: " + String.format("%.2f", currentVoltage) + "V");
// Battery status analysis
if (currentVoltage >= 12.0) {
System.out.println("🟢 Battery Status: GOOD");
} else if (currentVoltage >= 11.5) {
System.out.println("🟡 Battery Status: MODERATE");
} else if (currentVoltage >= 11.0) {
System.out.println("🟠 Battery Status: LOW");
lowBatteryWarnings++;
} else {
System.out.println("🔴 Battery Status: CRITICAL - STOP ROBOT!");
lowBatteryWarnings++;
System.out.println("⚠️ Automatic shutdown triggered!");
break; // Critical battery - emergency stop
}
// Show average
if (readingCount > 0) {
double average = totalVoltage / readingCount;
System.out.println("Average voltage: " + String.format("%.2f", average) + "V");
}
} else if (command.equals("status")) {
System.out.println("\n=== Battery Status Report ===");
System.out.println("Current voltage: " + String.format("%.2f", currentVoltage) + "V");
System.out.println("Readings taken: " + readingCount);
System.out.println("Low battery warnings: " + lowBatteryWarnings);
} else if (command.equals("help")) {
System.out.println("\nAvailable commands:");
System.out.println(" reading - Take a battery voltage reading");
System.out.println(" status - Show battery status report");
System.out.println(" exit - Exit battery monitor");
System.out.println(" help - Show this help");
} else {
System.out.println("❌ Unknown command: " + command);
System.out.println("Type 'help' for available commands.");
}
}
// Final report
System.out.println("\n=== Final Battery Report ===");
System.out.println("Total readings: " + readingCount);
System.out.println("Final voltage: " + String.format("%.2f", currentVoltage) + "V");
System.out.println("Low battery warnings: " + lowBatteryWarnings);
if (readingCount > 0) {
double average = totalVoltage / readingCount;
System.out.println("Average voltage: " + String.format("%.2f", average) + "V");
}
System.out.println("Battery monitor shutdown complete.");
}
}
Make a number guessing game with user input validation
Make a number guessing game with user input validation
import java.util.Scanner;
import java.util.Random;
public class NumberGuessingGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
// Game setup
int targetNumber = random.nextInt(100) + 1; // 1-100
int attempts = 0;
int maxAttempts = 7;
boolean gameWon = false;
System.out.println("=== Robot Sensor Calibration Game ===");
System.out.println("The robot sensor needs calibration!");
System.out.println("Guess the correct sensor value (1-100)");
System.out.println("You have " + maxAttempts + " attempts.");
while (true) {
System.out.print("\nAttempt " + (attempts + 1) + " of " + maxAttempts + ": ");
String input = scanner.nextLine().trim();
// Check for quit command
if (input.equalsIgnoreCase("quit") || input.equalsIgnoreCase("exit")) {
System.out.println("Game ended. The sensor value was: " + targetNumber);
break;
}
// Validate input
int guess;
try {
guess = Integer.parseInt(input);
} catch (NumberFormatException e) {
System.out.println("❌ Invalid input! Please enter a number (1-100) or 'quit'");
continue; // Don't count invalid inputs as attempts
}
// Check range
if (guess < 1 || guess > 100) {
System.out.println("❌ Out of range! Enter a number between 1 and 100.");
continue; // Don't count out-of-range as attempts
}
// Count valid attempt
attempts++;
// Check guess
if (guess == targetNumber) {
gameWon = true;
System.out.println("🎉 CORRECT! Sensor calibrated successfully!");
System.out.println("You found the value " + targetNumber + " in " + attempts + " attempts.");
break;
} else if (guess < targetNumber) {
int difference = targetNumber - guess;
System.out.println("📈 Too low! Sensor needs higher calibration.");
if (difference <= 5) {
System.out.println("🔥 Very close! You're within 5 points.");
} else if (difference <= 15) {
System.out.println("⚡ Getting warmer!");
}
} else {
int difference = guess - targetNumber;
System.out.println("📉 Too high! Sensor needs lower calibration.");
if (difference <= 5) {
System.out.println("🔥 Very close! You're within 5 points.");
} else if (difference <= 15) {
System.out.println("⚡ Getting warmer!");
}
}
// Check if attempts exhausted
if (attempts >= maxAttempts) {
System.out.println("\n💥 Game Over! No more attempts remaining.");
System.out.println("The correct sensor value was: " + targetNumber);
break;
}
// Show remaining attempts
int remaining = maxAttempts - attempts;
System.out.println("Attempts remaining: " + remaining);
}
// Game summary
System.out.println("\n=== Game Summary ===");
System.out.println("Target value: " + targetNumber);
System.out.println("Attempts used: " + attempts);
if (gameWon) {
if (attempts == 1) {
System.out.println("🏆 PERFECT! First try calibration!");
} else if (attempts <= 3) {
System.out.println("⭐ EXCELLENT! Quick calibration!");
} else if (attempts <= 5) {
System.out.println("✅ GOOD! Efficient calibration.");
} else {
System.out.println("✅ SUCCESS! Sensor calibrated.");
}
} else {
System.out.println("❌ Calibration failed. Try again!");
}
System.out.println("Calibration session complete.");
}
}
Create a sensor reading loop that stops when target value is reached
Create a sensor reading loop that stops when target value is reached