Transcripted Summary

In this chapter, we'll discuss repetition structures, also commonly known as loops.

You'll learn about the three different kinds of loops:

• While
• Do While
• For

Repetition Structures - Loops

Loops are structures that cause a block of code to repeat.

In most cases when you need your code to repeat the same statements more than once, it's best to wrap them within a loop. This eliminates the redundant act of copying and pasting those same statements over and over again. Programmers use the mnemonic DRY, which stands for Don't Repeat Yourself.

We'll need to calculate the salary for employees based on how many hours they have worked. This one says our program cannot allow for overtime, which means we need to validate the input.

Let's start off with the While loop by coding this example.

We have a new package, chapter4, and a new class inside of this package, GrossPayInputValidation.

I initialized the known variables:

• so we know that the rate is \$15 an hour
• and we'll go ahead and say that the max hours they can work is 40

Next, I went ahead and got the unknown variables:

• I asked them how many hours they worked that week
• and scanned it in
package chapter4;

/*
* WHILE LOOP:
* Each store employee makes \$15 an hour. Write a program that allows the employee
* to enter the number of hours worked for the week. Do not allow overtime.
*/
public class GrossPayInputValidation {

public static void main(String args[]){

//Initialize known variables
int rate = 15;
int maxHours = 40;

//Get input for unknown variables
System.out.println("How many hours did you work this week?");
Scanner scanner = new Scanner(System.in);
double hoursWorked = scanner.nextDouble();
}
}

Now, since we are not to allow overtime, we have to verify that what they've entered is valid input.

We could check to make sure that hours worked is not greater than 40, however, what if they enter the wrong input again? Or a third time, or a fourth time? How we will know once it's valid?

We could do this via a loop.

The loop will verify that the input is valid. If it is not it will continue looping until that input is valid.

So, letâ€™s add a new section within the method:

//Validate input

And we're going use the While loop.

You simply write the word while, and then in parenthesis this takes a condition. So, we want to say, "While the hours worked is greater than the max hours" â€” meaning the input that they've provided is greater than what's allowed, so it's invalid, and then we put curly braces.

//Validate input
while(hoursWorked > maxHours) {

}

If this condition is true (hoursWorked > maxHours), it will go inside of this loop.

So inside of here we want to then let them know that it was invalid.

//Validate input
while(hoursWorked > maxHours) {
System.out.println("Invalid entry. Your hours must be between 1 and 40. Try again.");
}

Now, I've outputted an error message, which is really important. When you're validating something, you want to let people know what they've done wrong so that they don't make the mistake again.

So now that we've told them that they can try again, we need to read this information in again.

So, weâ€™re going to use that same hoursWorked variable, and we're going to update it with their new input.

//Validate input
while(hoursWorked > maxHours) {
System.out.println("Invalid entry. Your hours must be between 1 and 40. Try again.");
hoursWorked = scanner.nextDouble();
}

This will allow them a second chance to enter a value for how many hours they've worked. Once they've entered this, it will exit this loop, come back to the top while(hoursWorked > maxHours) and it will test this condition again.

So, hoursWorked has been updated, now its new value will be compared with the maxHours.

If this is still true, meaning they enter something greater than 40 yet again, it will go back inside of the loop. hoursWorked will get updated again. It'll come back to the top of the loop to test the condition again. Once they've actually put in valid data, the condition will then become false and it will exit the loop and continue with the program.

Now it's up to you as the programmer to make sure that your loops do not run infinitely.

The way you do that is by using, like we've done here, a variable that will be updated at some point within the loop. This is called a sentinel.

Sentinels

A sentinel is a variable used within the condition that controls the loop.. It's very important that somewhere in your loops there's an opportunity for the sentinel to be updated. Otherwise, this loop will run infinitely.

For example, if I assigned their input to a new variable, instead of to hoursWorked:

//Validate input
while(hoursWorked > maxHours) {
System.out.println("Invalid entry. Yours hours must be between 1 and 40. Try again.");
double anotherVariable = scanner.nextDouble();
}

This loop will continue running forever. Because when they enter the new data, I'm storing it in anotherVariable, but the condition that controls the loop is hoursWorked > maxHours. Since neither of these variables hoursWorked or maxHours are getting updated within the loop, the condition never changes. Therefore, the condition will always be true until we run out of space on the computer and the program crashes.

That's why it's very important to make sure you use your sentinel. So whatever variable you're using within your condition that controls this loop, make sure that it's getting updated inside of the loop.

Okay, let's go ahead and close the scanner now, calculate the growth and print out the statement.

//Validate input
while(hoursWorked > maxHours || hoursWorked < 1){
System.out.println("Invalid entry. Your hours must be between 1 and 40. Try again.");
hoursWorked = scanner.nextDouble();
}

scanner.close();

//Calculate gross
double gross = rate * hoursWorked;
System.out.println("Gross pay: \$" + gross);

Letâ€™s run this.

### # GrossPayInputValidation.java

package chapter4;

import java.util.Scanner;

/*
* WHILE LOOP:
* Each store employee makes \$15 an hour. Write a program that allows the employee
* to enter the number of hours worked for the week. Do not allow overtime.
*/
public class GrossPayInputValidation {

public static void main(String args[]){

//Initialize known variables
int rate = 15;
int maxHours = 40;

//Get input for unknown variables
System.out.println("How many hours did you work this week?");
Scanner scanner = new Scanner(System.in);
double hoursWorked = scanner.nextDouble();

//Validate input
while(hoursWorked > maxHours){
System.out.println("Invalid entry. Your hours must be between 1 and 40. Try again.");
hoursWorked = scanner.nextDouble();
}

scanner.close();

//Calculate gross
double gross = rate * hoursWorked;
System.out.println("Gross pay: \$" + gross);
}
}

So, let's go ahead and say that we worked 80 hours this week.

Notice it came here, compared that 80 > 40, this is true, so it went inside of the loop. We got the invalid entry. "Your hours must be between 1 and 40."

Now we can say 35, and we see it doesnâ€™t go inside of the loop. It continues with the program, executing everything else.

Now, we're going to update this condition to be a little bit better.

Since we said it needs to be between 1 and 40, the only condition we're checking here is that it's greater than 40, so let's make sure that it's also not less than 1.

//Validate input
while(hoursWorked > maxHours || hoursWorked < 1){
System.out.println("Invalid entry. Yours hours must be between 1 and 40. Try again.");
hoursWorked = scanner.nextDouble();
}

Let's run this again, just to test that condition.

• So, let's say -8. And 0. Great.
• And let's just make sure we didn't mess up our big condition. Weâ€™ll enter 67. Great.
• And then right at 40 should work. Perfect.

### # Key Points of While Loop

So here are the key points about the While loop.

• Itâ€™s controlled by a condition and will continue to run while that condition remains true.

• The condition is tested before the loop is entered, so there's a chance that this loop will never execute.

• It's good to use the While loop when you may or may not need to run the loop, based on the state of the condition.

### # Steps of While Loop

Now let's review the steps of a While loop.

1. First the condition is evaluated to determine if the loop needs to be executed.

2. If that's true, the statements inside of the loop are executed.

3. Then the condition is rechecked to determine if to run the loop again.

Remember to update the sentinel inside of your loop.

## Resources

Quiz

The quiz for Chapter 4 can be found at the end of Section 4d