3.4 Looping
Loops in Java allow you to repeat a block of code, which is essential for tasks like iterating through arrays, lists, or processing repetitive tasks. By using loops, you can reduce redundancy and automate repetitive tasks efficiently.
Key Topics:
- The
forLoop: Iterate a set number of times. - The
whileLoop: Repeat while a condition is true. - The
do-whileLoop: Execute code at least once and repeat based on a condition.
Looping in Java is essential for:
- Repetitive tasks: Efficiently performing actions multiple times.
- Iterating over collections: Processing elements in arrays, lists, and sets.
- Dynamic behavior: Creating flexible and responsive applications.
- Algorithm implementation: Building foundational components for algorithms.
By effectively using loops, you can write more efficient, concise, and powerful Java code.
public class OnlineStore {
public static void main(String[] args) {
// Product details
String[] products = {"Product A", "Product B", "Product C"};
double[] prices = {10.99, 15.99, 29.99};
int[] quantities = {0, 0, 0};
// Shopping cart loop
boolean isShopping = true;
while (isShopping) {
System.out.println("Menu:");
System.out.println("1. Add to cart");
System.out.println("2. View cart");
System.out.println("3. Checkout");
System.out.print("Enter your choice: ");
int choice = Integer.parseInt(new java.util.Scanner(System.in).nextLine());
switch (choice) {
case 1:
System.out.println("Products:");
for (int i = 0; i < products.length; i++) {
System.out.println((i + 1) + ". " + products[i] + " - $" + prices[i]);
}
System.out.print("Enter product number: ");
int productIndex = Integer.parseInt(new java.util.Scanner(System.in).nextLine()) - 1;
if (productIndex >= 0 && productIndex < products.length) {
System.out.print("Enter quantity: ");
int quantity = Integer.parseInt(new java.util.Scanner(System.in).nextLine());
quantities[productIndex] += quantity;
System.out.println("Product added to cart.");
} else {
System.out.println("Invalid product number.");
}
break;
case 2:
System.out.println("Your cart:");
for (int i = 0; i < products.length; i++) {
if (quantities[i] > 0) {
System.out.println(products[i] + " - $" + prices[i] + " x " + quantities[i] + " = $" + (prices[i] * quantities[i]));
}
}
break;
case 3:
double total = 0;
for (int i = 0; i < products.length; i++) {
total += prices[i] * quantities[i];
}
System.out.println("Total: $" + total);
// Add payment processing logic here
isShopping = false;
break;
default:
System.out.println("Invalid choice.");
}
}
}
}
The for Loop
The for loop is used to repeat a block of code a specific number of times, often used to iterate over arrays, lists, or ranges of numbers.
Syntax:
for (initialization; condition; update) {
// Code to execute for each iteration
}
Example:
for (int i = 0; i < 5; i++) {
System.out.println(i); // This will print numbers from 0 to 4
}
Real-World Use Case:
A common use of the for loop is to iterate over an array of product prices and apply a discount to each one.
double[] prices = {100, 200, 300, 400, 500};
double discount = 0.10;
for (int i = 0; i < prices.length; i++) {
prices[i] = prices[i] - (prices[i] * discount); // Apply a 10% discount to each price
System.out.println("New price: " + prices[i]);
}
You can exit a loop prematurely using the break keyword, which stops the loop entirely. Alternatively, you can use the continue keyword to skip the current iteration and move to the next one without stopping the loop. All these keywords and conditions in loops should be applied as per your program's needs to satisfy the business logic you are building.
The while Loop
The while loop continues to execute as long as a specified condition is true.This is also refered as entry control loop as it check condition before executing anything in the loop's block. This type of loop is useful when the number of iterations is not known in advance and depends on a condition being met.
Syntax:
while (condition) {
// Code to execute while the condition is true
}
A while loop can be used to simulate a login attempt system, where the user has multiple attempts to enter the correct password.
Example:
import java.util.Scanner;
public class LoginSystem {
public static void main(String[] args) {
int failedLoginAttemptCount = 0;
Scanner scanner = new Scanner(System.in);
//We are putting a limit on Failed Login Attempt using While loop
while (failedLoginAttemptCount < 3) {
System.out.print("Enter username: ");
String username = scanner.nextLine();
System.out.print("Enter password: ");
String password = scanner.nextLine();
if (isLoginSuccessful(username, password)) {
System.out.println("Login successful!");
break; // Exit the loop if login is successful
} else {
failedLoginAttemptCount++;
System.out.println("Login failed. Attempt " + failedLoginAttemptCount + " of 3.");
}
}
if (failedLoginAttemptCount == 3) {
System.out.println("Too many failed attempts. Access locked.");
}
}
// Simulated login check method
public static boolean isLoginSuccessful(String username, String password) {
// In a real-world application, this method would check credentials against a database.
return username.equals("admin") && password.equals("password123");
}
}
- While loops repeatedly execute a block of code as long as the condition remains true. It's useful when you don't know how many iterations are needed in advance.
- Be cautious of infinite loops: Always ensure the condition eventually becomes false to avoid the program getting stuck.
- You can exit the loop early using the
breakkeyword, and you can skip to the next iteration using thecontinuekeyword. - While loops are often used for scenarios like user input validation, waiting for a resource, or processing until a certain state is reached.
The do-while Loop
The do-while loop guarantees that the code inside the loop is executed at least once before the condition is checked.
Syntax:
do {
// Code to execute at least once
} while (condition);
Example:
int x = 0;
do {
System.out.println(x);
x++; // This will print numbers from 0 to 4
} while (x < 5);
Real-World Use Case:
A do-while loop can be used when prompting users to input data, ensuring the prompt is displayed at least once even if the condition is already false.
String input = "";
Scanner scanner = new Scanner(System.in);
do {
System.out.println("Enter 'exit' to quit:");
input = scanner.nextLine();
} while (!input.equals("exit"));
System.out.println("Program terminated.");
For Loop: Ideal when you know the exact number of iterations, often used for iterating through arrays or lists. It provides a simple, controlled structure to repeat a block of code a set number of times.
While Loop: Suitable when the number of iterations isn’t known upfront. It repeats as long as a condition remains true, making it perfect for scenarios like waiting for a specific event or user input.
Do-While Loop: Ensures the code block runs at least once, regardless of the condition. It's often used when an action needs to be performed at least once before checking the condition, like prompting for user input.
ForEach Loop: Used to iterate through collections like arrays and lists. It's concise and ideal when you need to process each element in a collection without the need for index-based access.
By understanding and using these loops appropriately, you can handle a wide range of scenarios efficiently in Java.
Conclusion
Loops are a fundamental part of programming, allowing you to efficiently repeat actions without duplicating code. The for loop is ideal for iterating a fixed number of times, while the while loop is better for situations where the number of iterations is determined by a condition. The do-while loop ensures that a block of code is executed at least once before the condition is checked, making it useful in scenarios where user input is required.
By mastering loops, you can write more efficient and readable code that can handle repetitive tasks with ease.