Introduction to Java using NetBeans

Section 6 : Loops



The while Loop

The while loop is a loop that repeats as long as the condition is true.

The condition of the while loop is evaluated before the statements are executed.

When the condition is true, the statements are executed; when the condition is false, the program flow continues to the next statement after the closing curly brace of the while loop.

Syntax (How to use the while Loop):

while (condition){ 
     statement 1; 
     statement 2;

Example Icon Example 4

int i = 1;

while (i <= 5){

This image shows the output window for example 4.



The do-while Loop

The do-while loop is an alternative form of the while statement. In the do-while statement, the condition is not evaluated until after the first execution of the loop. Therefore, the do-while loop always executes at least once.

Syntax (How to use the do.. while Loop):

do {
statement 1;
statement 2;
}while (condition);

Example Icon Example 5

// do while loop

int j = 5;

} while (j < 5);

This image shows the output window for example 5.



Assignment 6.2 - Certificates of Deposit

A certificate of deposit (CD) is a type of investment that matures at a specified interest rate for a specified period.

Create a CD Calculator application that accepts input for:

  • The initial investment amount
  • The annual interest rate
  • The desired ending value

The application should then display the number of years required for a CD to be worth the specified ending value when the interest is compounded annually.

The CD value at the end of each year can be calculated by the formula:

CD Value = CD Value + (CD Value * Interest Rate)

To determine the number of years it will take for the CD to reach the desired ending value, repeatedly execute the formula until the CD Value is greater than or equal to the desire ending value.

Hint: Use a while loop and a counter.
The application interface should look similar to:

This shows a possible output of the CD Calculator program.



Assignment 6.3 - CarRecall (Console)

Cars from the Ford plant need to be recalled. Model numbers 119, 179, 189 through 195 and 221 have been found to be defective because their wheels are not perfectly round. Create an application that allows the mechanic to repeatedly enter in model numbers and be told whether the car is defective or not. The mechanic can stop the application any time by entering a -1