Java While Loops and Do While Loops
Java Iteration: While Loops and Do While Loops
Definition of Iteration
Iteration is defined as the repetition of code for a specified number of times.
Both while loops and for loops fall under this definition of iteration.
While Loop
A while loop is a type of loop that executes code inside it when a specified condition is true.
The condition for a while loop is a logical test, akin to the conditions used in if statements.
Execution Flow:
If the logical test evaluates to true, the code inside the while loop executes.
If the test evaluates to false, the loop skips the code inside and continues; the execution moves past the loop.
Key Characteristics
It keeps executing as long as the condition remains true, which distinguishes it from if statements.
After executing the inner code, the loop will re-evaluate the condition; if still true, it will keep executing.
Example of a While Loop
An example of using a while loop could involve:
Asking the user for the number of items they purchased at a restaurant.
Requesting a tip from the user, subsequently calculating the tip and the final bill.
Code Example:
import javax.swing.JOptionPane;
double subtotal = 0.0;
String input = JOptionPane.showInputDialog("Enter item cost (or Cancel to finish):"); // Primer input
while (input != null && !input.isEmpty()) {
try {
double itemCost = Double.parseDouble(input);
subtotal += itemCost;
input = JOptionPane.showInputDialog("Enter item cost (or Cancel to finish):"); // Update input
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Invalid input. Please enter a number.");
input = JOptionPane.showInputDialog("Enter item cost (or Cancel to finish):");
}
}
JOptionPane.showMessageDialog(null, "Total subtotal: $" + String.format("%.2f", subtotal));
Primer Requirement
Some while loops require a primer: an initial input that allows the loop to start.
In the restaurant calculation example, the primer ensures that user input is received to prevent the loop from failing to execute.
Infinite Loops
Infinite loops can occur when the condition remains perpetually true, preventing subsequent code from executing.
Example:
If an integer variable
xis initialized with a value of 5, and a condition checks if it is greater than 2, since 5 is always greater than 2, the loop will execute indefinitely.
Prevention: To avoid infinite loops, ensure the test condition is updated during each iteration. For example, decreasing
xafter each pass until it eventually becomes false.
Do While Loop
A do while loop is an alternative to the while loop where the code is executed first before the condition is tested.
Unlike the while loop, a do while loop does not require a primer, as execution starts prior to the test.
Structure of Do While Loop
Syntax:
java do { // code to execute } while (condition);The execution occurs first in the
dosection, and only after the code has run does it evaluate the condition stated in thewhileclause.
Example of Do While Loop
In the restaurant calculation example using a do while loop:
The loop prompts for the cost of a purchase and directly executes that code.
Immediately checks if the input is valid before performing calculations, thus avoiding the need for a primer.
Code Example:
import javax.swing.JOptionPane;
double subtotal = 0.0;
String input;
do {
input = JOptionPane.showInputDialog("Enter item cost (or Cancel to finish):");
if (input != null && !input.isEmpty()) {
try {
double itemCost = Double.parseDouble(input);
subtotal += itemCost;
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Invalid input. Please enter a number.");
}
}
} while (input != null && !input.isEmpty()); // Condition checked after execution
JOptionPane.showMessageDialog(null, "Total subtotal: $" + String.format("%.2f", subtotal));
Differences Between While and Do While Loops
While Loop:
Requires a primer under certain conditions to begin execution.
Tests the condition before running the code block.
Do While Loop:
Executes the code before it checks the condition.
Does not require an initial input or primer, but still performs a necessary validation.
Importance of Validation
In scenarios where user input is deemed nullable, adding validation checks helps to avoid exceptions such as
NullPointerException.Without appropriate checks, if the input provided by users is null, code execution risks leading to runtime errors.
Practical Demonstrations
While Loop Demonstration
Initialization: Import necessary classes (e.g.,
java.text.DecimalFormatfor formatting currency,javax.swing.JOptionPanefor GUI inputs).$decimalFormat dollar = new DecimalFormat("0.00")$
Structure:
Set up variables such as
double subtotal = 0.0for maintaining the running total of purchases, tips, taxes.The while loop prompts for input, validating whether the input is null, and adds valid purchases to the subtotal until canceled.
Do While Loop Demonstration
Similar setup but executes the input request before checking if the value is valid, which simplifies user interaction and streamlines the portion of the code dedicated to acquiring inputs.
Summary
This tutorial comprehensively addresses how while loops and do while loops function within Java programming.
Focus is placed on understanding iteration, conditions, primers, and the practical application of loops through a restaurant billing example.
The next video will introduce the for loop, which possesses a more structured nature compared to the while loop.