Java
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented Java
-
Section 4: Collections Framework
-
Section 5: Exception Handling
-
Section 6: Generics
-
Section 7: Functional Java
-
Section 8: Concurrency
-
Section 9: I/O and NIO
-
Section 10: JVM Internals
-
Section 11: Modern Java Features
-
Section 12: Build Tools and Project Structure
-
Section 13: Testing
-
Section 14: Databases and Persistence
-
Section 15: Networking
-
Section 16: Design and Best Practices
-
Section 17: Reflection and Annotations
-
Section 18: Logging and Diagnostics
-
Section 19: Date, Time, and Internationalization
-
Section 20: Java Platform Module System
-
Section 21: Security in Java
-
Section 22: Advanced Collections and Data Structures
-
Section 23: More Concurrency Patterns
-
Section 24: Compression, Files, and System Integration
-
Section 25: GUI Programming
-
Section 26: Practical Projects
-
Section 27: Data Structures and Algorithms
-
Section 28: Interview and Algorithm Practice
-
Section 29: JSON and Data Interchange
-
Section 30: More Concurrency Utilities
-
Section 31: More Collections and Streams Practice
-
Section 32: More File and System Programming
-
Section 33: Standard Library Deep Dive
-
Section 34: More Practice and Drills
-
Section 35: More Testing and Quality
-
Section 36: More Design Patterns and Architecture
-
Section 37: Career and Ecosystem
-
Section 38: More OOP and Architecture Practice
-
Section 39: More Enterprise Concepts
-
Section 40: Advanced JavaFX
-
Section 41: More Interview Practice
16: While and Do-While Loops
I've been working on a small RPG prototype today, and I hit a bit of a snag with how the character heals. I wanted to simulate a "healing potion" that ticks up the character's health over time until they are fully recovered. Initially, I thought about using a for loop, but as I started typing, I realized it felt wrong.
The problem with knowing the end date
Here is what I first tried. I knew the character had 20 HP and a max of 100, so I tried to calculate exactly how many iterations I needed:
int health = 20;
int maxHealth = 100;
int healAmount = 10;
for (int i = 0; i < (maxHealth - health) / healAmount; i++) {
health += healAmount;
System.out.println("Healing... Current health: " + health);
}
It works, but it's brittle. What if the healAmount changes mid-way? What if a random event causes the character to take damage while they are healing? Using a for loop here forces me to do math upfront to determine the number of cycles. In a real game, you rarely know exactly how many times something will happen; you just know when it should stop happening.
Letting the condition drive the bus
I decided to scrap the for loop and try a while loop instead. The logic is simpler: "While the health is less than the max, keep adding health." No pre-calculating the number of iterations required.
int health = 20;
int maxHealth = 100;
int healAmount = 10;
while (health < maxHealth) {
health += healAmount;
System.out.println("Healing... Current health: " + health);
}
This feels much more natural. The loop doesn't care if it runs 8 times or 800 times; it only cares about that boolean condition (health < maxHealth). If the condition is true, it runs. The moment it becomes false, it exits. This is the core strength of the while loop—it's for when the number of iterations is unknown.
The infinite loop trap
Now, I'll be honest: even after years of doing this, I still occasionally make the "infinite loop" mistake. I tried to add a feature where the healing amount could randomly fluctuate, and I accidentally commented out the line that actually increases the health.
while (health < maxHealth) {
// health += healAmount; <--- I commented this out by mistake!
System.out.println("Healing... Current health: " + health);
}
I ran the code, and my console immediately exploded with thousands of "Healing... Current health: 20" messages. My CPU spiked, and I had to kill the process. Why? Because health stayed at 20, and 20 < 100 is always true. If the condition inside a while loop never becomes false, your program will run until it crashes or you force it to stop. Always double-check that something inside your loop is actually moving you toward the exit condition.
Doing it once before asking
Finally, I wanted to add a "Manual Heal" option where the player presses a key to heal. I wanted the character to heal once, and then ask if they want to do it again. If I use a standard while loop, I have to check the condition before the first heal even happens, which means I might have to initialize my "continue" variable to true just to get it started.
That's where the do-while loop comes in. It's a slight variation that guarantees the code block runs at least once before checking the condition.
Scanner scanner = new Scanner(System.in);
int health = 20;
int maxHealth = 100;
char choice;
do {
health += 10;
System.out.println("Healed! Current health: " + health);
System.out.print("Heal again? (y/n): ");
choice = scanner.next().charAt(0);
} while (choice == 'y' && health < maxHealth);
Notice the difference: the do block executes first, and the while check happens at the very bottom. I didn't have to "prime" the loop by setting choice = 'y' beforehand. I just did the action, then asked if we should repeat it. If the player types 'n' or their health hits 100, the loop terminates.
📋 Practical Task
Build a Stamina-Based Sprint System
Create a program that simulates a character sprinting. The character starts with 100 stamina. Every "step" they take consumes a random amount of stamina between 5 and 15. Use a while loop to keep the character sprinting as long as their stamina is above 0.
Requirements:
- Initialize
staminaat 100. - Inside the loop, use
(int)(Math.random() * 11) + 5to generate a random stamina cost. - Subtract that cost from the total stamina and print the remaining stamina after each step.
- Once the loop ends, print a message saying "Out of breath!"
- Bonus: Wrap the entire logic in a
do-whileloop that asks the user if they want to "Run another lap?" after the character has run out of breath.
There are no comments for now.