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 indefinite, pre-test loops. While these loops can be used to iterate a set number of times, they are powerful and can be used to iterate until a user meets a condition, like enters a particular value or clicks on a desired object. These loops test a condition, a Boolean expression, at the start of the loop and if the condition is true
the statements inside the body of the while
loop are executed. Because they test the loop at the start, it is a pre-test loop.
Because a while
loop tests at the beginning, it may or may not execute at all. If the condition 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) {
//statements we want to repeat
}
Let's look at some examples:
Looping a Set Number of Times
This code will loop until value
is greater than 10 and output even numbers to the screen.
Prompting For a Positive Valuea
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, is if you sign up for an account and you haven't filled in all the required fields, it will keep prompting you to do so until all the currently blank required fields have values.
You can try this code in an IDE. Unfortunately, the Java Playground does not allow for input.
Scanner input = new Scanner(System.in);
int value = -1;
while (value <= 0) {
println("Enter a positive number");
value = input.nextInt();
}
println(value);
Computing Your Average
This program prompts the user to enter in grades or 999 if no more grades are available. It updates totalGrades
by adding the 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;
Scanner input = new Scanner(System.in);
while (grade != 999) {
println("Enter a grade. Enter 999 to stop.");
grade = input.nextInt();
if (grade != 999) {
totalGrades += grade;
numGrades++;
}
}
double average = totalGrades / numGrades;
println(average);
Spending Calculator
This program 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;
int purchaseAmount = 0;
boolean morePurchases = true;
Scanner input = new Scanner(System.in);
while (morePurchases && spendingMoney > 0) {
println("Do you have more purchases? Enter true for yes, false for no.");
morePurchases = input.nextBoolean();
if (morePurchases) {
println("How much money did you spend?");
purchaseAmount = input.nextInt();
spendingMoney -= purchaseAmount;
}
}
println("You have $" + spendingMoney + " left.");
Resources