Skip Top Navigation Bar

Using While Loops

As we saw in our algorithms section, we will want our programs to repeat processes. We could write these statements multiple times to repeat processes, but sometimes we don't know how many times we want to repeat the statements. Not to mention, if we have a process that is going to repeat 100, 1000, a million times, it becomes unrealistic to repeat these lines of code. Instead, we can use an iterative statement to repeat the code. There are multiple type of iterative statements. In this lesson, we will use while loops to create iteration in our programs.

While Loops

While loops are considered pre-test loops. These loops can be used to iterate a set number of times as well as until a condition is met, like the user enters a particular value or clicks on a desired object. Pre-test loops, like while loops, test a Boolean expression, at the start of the loop and if the Boolean expression is true the statements inside the body of the while loop are executed.

Because a while loop is a pre-test loop, it may or may not execute at all. If the Boolean expression is false to start, the body of the loop is not executed.

The general format of a while loop is as follows:

while (<boolean expression>) { 
    //Body of the Loop - statements we want to repeat if the boolean expression is true
}

Tracing While Loops


Your Turrn

Let's try it in the Java Playground

Prompting For a Positive Values

When using readln and readln(String prompt), input is received as type String. If we are trying to read in primitive values, such as int, double, boolean, we will need to use parsing methods from the wrapper classes. Learn about these methods in the Wrapper Classes Tutorial

This code continues to read in values until a positive value is entered. This is a way that you can safeguard your program against users not entering the right type of data. Some examples of where you might have experienced a program safeguarding your input:

The Java Playground does not allow input, so try this code in an IDE.

int value = -1;
while (value <= 0) {
   String input = IO.readln("Enter a positive number");
   value = Integer.parseInt(input);
}
IO.println(value);

Computing Your Average

The program below prompts the user to enter in grades or 999 if no more grades are available. It updates totalGrades by adding each grade to the total and increases numGrades by 1. Once all the grades are entered, it computes the average. It's important to initialize the totalGrades and numGrades to 0 before any grades are entered. These variables need an initial value in order to be a part of a sum. The variable grades could be set to anything other than 999, which is what is entered to stop the iteration. Note that an if statement is used to ensure that 999 is not added to totalGrades and numGrades is not increased.

Try this in an IDE.

int totalGrades = 0;
int numGrades = 0;
int grade = 0;
while (grade != 999) {
   String input = IO.readln("Enter a grade. Enter 999 to stop.");
   grade = Integer.parseInt(input);
   if (grade != 999) {
      totalGrades += grade;
      numGrades++;
   }
}
double average = totalGrades / numGrades;
IO.println(average);

Spending Calculator

The program below keeps track of your available spending money and subtracts your purchases. The loop ends if there are no more purchases or if the amount of spending money is less than or equal to 0.

Try this in an IDE.

int spendingMoney = 100; 
double purchaseAmount = 0;
String morePurchases = "yes"; 
while (morePurchases.equals("yes") && spendingMoney > 0) {
   String morePurchases = IO.readln("Do you have more purchases? Enter true for yes, false for no.");
   if (morePurchases.equals("yes")) {
      String input = IO.readln("How much money did you spend?");
      purchaseAmount = Double.parseDouble(input);
      spendingMoney -= purchaseAmount;
   }
}
IO.println("You have $" + spendingMoney + " left.");

Resources

Next Learn Tutorial