Module 1: Loops
Module Overview
Learn about the different types of loops in Java, when to use each type, and how to write efficient loop structures.
Learning Objectives
- Implement repetitive execution of a code block using a while statement
- Implement repetitive execution of a code block using a for statement
- Implement repetitive execution of code blocks using nested looping statements
- Use a break statement to interrupt execution of a loop
- Use a continue statement to skip an iteration of a loop
- Predict the resulting values of variables modified by several iterations of a loop in a code snippet
Loop Concepts Explained
While Loops
A while loop executes a block of code as long as its condition remains true.
// Example: Counting from 1 to 5 using a while loop
int count = 1;
while (count <= 5) {
System.out.println("Count is: " + count);
count++;
}
For Loops
A for loop provides a compact way to iterate over a range of values with initialization, condition, and iteration expressions.
// Example: Counting from 1 to 5 using a for loop
for (int i = 1; i <= 5; i++) {
System.out.println("Count is: " + i);
}
Nested Loops
Nested loops place one loop inside another, often used for working with multi-dimensional data.
// Example: Printing a simple pattern using nested loops
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
Loop Control Statements
Break and continue statements allow you to control the flow of loop execution.
// Example: Using break to exit a loop early
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit the loop when i equals 5
}
System.out.println("Count: " + i);
}
// Example: Using continue to skip an iteration
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
System.out.println("Odd number: " + i);
}
Practical Applications
Loops are fundamental programming constructs with countless practical applications:
- Processing collections of data (arrays, lists, etc.)
- Repetitive tasks automation
- Input validation and retry mechanisms
- Game development (game loops)
- Search algorithms
- Data processing and analysis
Additional Resources
Mastery Task 7 - Loops
Mastery Task Guidelines
Mastery Tasks are opportunities to test your knowledge and understanding through code. When a mastery task is shown in a module, it means that we've covered all the concepts that you need to complete that task. You will want to make sure you finish them by the end of the week to stay on track and complete the unit.
Each mastery task must pass 100% of the automated tests and code styling checks to pass each unit. Your code must be your own. If you have any questions, feel free to reach out for support.
App Update
Inside of com.adventure.settings.AppSettings, update the story MT7_MonsterScene
Loops
We will be building an automated combat system that will involve loops as well as a file reader.
Working Classes
We will be working with the following classes:
- Monster (already built) - adventure.world.Monster
- CombatController - adventure.CombatController
- Player - adventure.player.Player
- SceneDescriptionFileReader - adventure.scenes.SceneDescriptionFileReader
Combat System
When a Player encounters a Monster, the game will build a CombatController that will pit the player and the monster into a battle.
Each fighter takes a turn hitting the other and the one that gets the other fighter to 0 health first, wins.
The amount of health points that are taken away is based on the fighter's power. So if the player has 10 health and the monster has a power of 2, then when the monster hits the player, the player's health goes down by 2 points and the player now has 8.
See the CombatController file for more information on how to properly implement its behavior.
Hint: only one loop should be necessary to complete this task.
Player
You will need to update Player.setWeapon(). See the function's comments to see how it should work.
File Reader
Reading files is perhaps the most common use case for while loops. That's because when you read in a file, you don't actually know how long the file is. For loops are used when we know how many iterations are required, so using a for loop here would not work.
This Sprint introduces the capability of scenes to have their descriptions inside of text files as opposed to being hardcoded in classes.
Read the class SceneDescriptionFileReader to learn about BufferedReader which is a class commonly used to read in files. It will tell you the essential characteristics of BufferedReader and how to successfully use it to read in a text file's contents.
For Windows Users: To avoid unnecessary errors, make sure the path to your project does not contain spaces.
Bad path: /my project/bd-java-fundamentals-1...
Good path: /MyProject/bd-java-fundamentals-1...
Testing
To run the tests for this assignment, run the following:
./gradlew test --tests com.adventure.MT7
or by right-clicking the MT7 file and selecting "Run 'MT7'"
You can check your code styling by running the linter with the following command:
./gradlew checkstyleMain
You can run the game by going to the Main class and clicking on the run icon to the left of the main() method.