Sunday, May 28, 2017

Introduction to Java programming, Part-1 (11)

Loops


Notwithstanding having the capacity to apply conditions to your projects and see distinctive results in light of different if/then situations, you once in a while need your code to do a similar thing again and again until the employment is finished. In this segment, find out about builds used to emphasize over code or execute it more than once.

What is a loop?

A loop is a programming construct that executes repeatedly while a specific condition (or set of conditions) is met. For instance, you might ask a program to read all records until the end of a data file, or to process each element of an array in turn. (You'll learn about arrays in the next section.)
Three loop constructs make it possible to iterate over code or execute it more than once:

  • for loops
  • while loops
  • do...while loops

⇒for loops

The basic loop construct in the Java language is the for statement. You can use a for statement to iterate over a range of values to determine how many times to execute a loop. The abstract syntax for a for loop is:
for (initialization; loopWhileTrue; executeAtBottomOfEachLoop) {
  statementsToExecute
}
At the beginning of the loop, the initialization statement is executed (multiple initialization statements can be separated by commas). Provided that loopWhileTrue (a Java conditional expression that must evaluate to either true or false) is true, the loop executes. At the bottom of the loop, executeAtBottomOfEachLoopexecutes.
For example, if you wanted the code in the main() method in Listing 8 to execute three times, you can use a for loop.
Listing 8. A for loop
1
2
3
4
5
6
7
8
9
10
11
12
13
public static void main(String[] args) {
  Logger l = Logger.getLogger(Person.class.getName());
  for (int aa = 0; aa < 3; aa++)
    Person p = new Person("Joe Q Author", 42, 173, 82, "Brown", "MALE");
    l.info("Loop executing iteration# " + aa);
    l.info("Name: " + p.getName());
    l.info("Age:" + p.getAge());
    l.info("Height (cm):" + p.getHeight());
    l.info("Weight (kg):" + p.getWeight());
    l.info("Eye Color:" + p.getEyeColor());
    l.info("Gender:" + p.getGender());
  }
}
The local variable aa is initialized to zero at the beginning of Listing 8. This statement executes only once, when the loop is initialized. The loop then continues three times, and each time aa is incremented by one.
You'll see in the next section that an alternative for loop syntax is available for looping over constructs that implement the Iterable interface (such as arrays and other Java utility classes). For now, just note the use of the for loop syntax in Listing 8.

⇒while loops

The syntax for a while loop is:
while (condition) {
  statementsToExecute
}
As you might suspect, if condition evaluates to true, the loop executes. At the top of each iteration (that is, before any statements execute), the condition is evaluated. If the condition evaluates to true, the loop executes. So it's possible that a while loop will never execute if its conditional expression is not true at least once.
Look again at the for loop in Listing 8. For comparison, Listing 9 uses a while loop to obtain the same result.
Listing 9. A while loop
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static void main(String[] args) {
  Logger l = Logger.getLogger(Person.class.getName());
  int aa = 0;
  while (aa < 3) {
    Person p = new Person("Joe Q Author", 42, 173, 82, "Brown", "MALE");
    l.info("Loop executing iteration# " + aa);
    l.info("Name: " + p.getName());
    l.info("Age:" + p.getAge());
    l.info("Height (cm):" + p.getHeight());
    l.info("Weight (kg):" + p.getWeight());
    l.info("Eye Color:" + p.getEyeColor());
    l.info("Gender:" + p.getGender());
    aa++;
  }
}
As you can see, a while loop requires a bit more housekeeping than a for loop. You must initialize the aavariable and also remember to increment it at the bottom of the loop.

⇒do...while loops

If you want a loop that always executes once and then checks its conditional expression, you can use a do...while loop, as shown in Listing 10.
Listing 10. A do...while loop
1
2
3
4
5
6
7
8
9
10
11
12
int aa = 0;
do {
  Person p = new Person("Joe Q Author", 42, 173, 82, "Brown", "MALE");
  l.info("Loop executing iteration# " + aa);
  l.info("Name: " + p.getName());
  l.info("Age:" + p.getAge());
  l.info("Height (cm):" + p.getHeight());
  l.info("Weight (kg):" + p.getWeight());
  l.info("Eye Color:" + p.getEyeColor());
  l.info("Gender:" + p.getGender());
  aa++;
} while (aa < 3);
The conditional expression (aa < 3) is not checked until the end of the loop.

Loop termination

At times, you need to bail out of — or terminate— a loop before the conditional expression evaluates tofalse. This situation can occur if you're searching an array of Strings for a particular value, and once you find it, you don't care about the other elements of the array. For the times when you want to bail, the Java language provides the break statement, shown in Listing 11.
Listing 11. A break statement
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static void main(String[] args) {
  Logger l = Logger.getLogger(Person.class.getName());
  int aa = 0;
  while (aa < 3) {
    if (aa == 1)
      break;
    Person p = new Person("Joe Q Author", 42, 173, 82, "Brown", "MALE");
    l.info("Loop executing iteration# " + aa);
    l.info("Name: " + p.getName());
    l.info("Age:" + p.getAge());
    l.info("Height (cm):" + p.getHeight());
    l.info("Weight (kg):" + p.getWeight());
    l.info("Eye Color:" + p.getEyeColor());
    l.info("Gender:" + p.getGender());
    aa++;
  }
}
The break statement takes you to the next executable statement outside of the loop in which it's located.

Loop continuation

In the (simplistic) example in Listing 11, you want to execute the loop only once and then bail. You can also skip a single iteration of a loop but continue executing the loop. For that purpose, you need the continuestatement, shown in Listing 12.
Listing 12. A continue statement
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public static void main(String[] args) {
  Logger l = Logger.getLogger(Person.class.getName());
  int aa = 0;
  while (aa < 3) {
    aa++;
    if (aa == 2)
      continue;
    Person p = new Person("Joe Q Author", 42, 173, 82, "Brown", "MALE");
    l.info("Loop executing iteration# " + aa);
    l.info("Name: " + p.getName());
    l.info("Age:" + p.getAge());
    l.info("Height (cm):" + p.getHeight());
    l.info("Weight (kg):" + p.getWeight());
    l.info("Eye Color:" + p.getEyeColor());
    l.info("Gender:" +
    p.getGender());
  }
}
In Listing 12, you skip the second iteration of a loop but continue to the third. continue comes in handy when you are, say, processing records and come across a record you don't want to process. You can skip that record and move on to the next one.
Previous Post
Next Post

post written by:

0 coment�rios: