CS 1063  Week 13: Do-While Loops

Objectives

Assignments


Sometimes you want to execute the body of a loop at least once and perform the loop test after the body was executed.  The do loop serves that purpose:

do {
   statement
} while ( condition );

The charAt method

The charAt method of the String class returns the character at a specified position with 0 being the beginning.

Examples:

Data Entry

One of the most common uses for the do-while loop is data entry.  Example:
import java.util.Scanner;

    Scanner in = new Scanner(System.in);
    char firstChar  = 'y';
    String answer = "";

    // loop while you keep getting answers starting with y
    do {
        statements here

        System.out.print("Would you like to continue? (y or n) ");
        answer = in.next();
        firstChar = answer.charAt(0);
    } while (firstChar == 'y');
Example:  Modify the GCD project from week 12 using a do loop to enter your data.

Activity 1:  Modifying the Investment project from week 12 using a do loop to repeatedly enter new data.

Scanner in = new Scanner(System.in);
char firstChar = ' ';

do {
   System.out.print("Enter the initial investment: ");
   double initialInvestment = in.nextDouble();
   System.out.print("Enter the rate as a decimal: ");
   double rate = in.nextDouble(); 
   System.out.print("Enter the target balance: ");
   double targetBalance = in.nextDouble();
   Investment invest = new Investment(initialInvestment, rate);
   System.out.println("Years = " + invest.yearsForBalance(targetBalance));

   System.out.print("Would you like to continue? (y or n) ");
   String answer = in.next();
   firstChar = answer.charAt(0);
} while (firstChar == 'y');

Activity 2:  Population

Write a class that will predict the size of a population of organisms.  The class should store the starting number of organisms, their average daily population increase (as a decimal) and the number of days they will multiply.  The class should have a method void growPopulation() that uses a whileloop to display the size of the population for each day including the original population.  Be sure and include the usual accessor methods  getPopulation, getDays, and getRate.

Test your class using the following data plus one set of your choice.  Use a do-while loop for continuous input until a 'n' or 'N' is entered.

Start: 10
Percent: 0.05
Days: 10