- Java Fundamentals
- Gazihan Alankus Rogério Theodoro de Brito Basheer Ahamed Fazal Vinicius Isola Miles Obare
- 2862字
- 2021-06-11 13:37:56
Looping Constructs
Looping constructs are used to perform a certain operation a given number of times as long as a condition is being met. They are commonly used to perform a specific operation on the items of a list. An example is when we want to find the summation of all the numbers from 1 to 100. Java supports the following looping constructs:
- for loops
- for each loops
- while loops
- do while loops
for Loops
The syntax of the for loop is as follows:
for( initialization ; condition ; expression) {
//statements
}
The initialization statements are executed when the for loop starts executing. It can be more than one expression, all separated by commas. The expressions must all be of the same type:
for( int i = 0, j = 0; i <= 9; i++)
The condition section of the for loop must evaluate to true or false. If there is no expression, the condition defaults to true.
The expression part is executed after each iteration of the statements, as long as the condition is true. You can have more than one expression separated by a comma.
Note
The expressions must be valid Java expressions, that is, expressions that can be terminated by a semicolon.
Here is how a for loop works:
- First, the initialization is evaluated.
- Then, the condition is checked. If the condition is true, the statements contained in the for block are executed.
- After the statements are executed, the expression is executed, and then the condition is checked again.
- If it is still not false, the statements are executed again, then the expression is executed, and the condition is evaluated again.
- This is repeated until the condition evaluates to false.
- When the condition evaluates to false, the for loop completes and the code sections after the loop are executed.
Exercise 8: Implementing a Simple for Loop
To print all the single digit numbers in increasing and decreasing order, perform the following steps:
- Right-click the src folder and select New | Class.
- Enter Looping as the class name, and then click OK.
- Set up the main method:
public class Looping
{
public static void main(String[] args) {
}
}
- Implement a for loop that initializes a variable i at zero, a condition so that the value remains below 10, and i should be incremented by one in each iteration:
System.out.println("Increasing order");
for( int i = 0; i <= 9; i++)
System.out.println(i);
- Implement another for loop that initializes a variable k at 9, a condition so that the value remains above 0, and k should be decremented by one in each iteration:
System.out.println("Decreasing order");
for( int k = 9; k >= 0; k--)
System.out.println(k);
Output:
Increasing order
0
1
2
3
4
5
6
7
8
9
Decreasing order
9
8
7
6
5
4
3
2
1
0
Activity 8: Implementing the for Loop
John, a peach grower, picks peaches from his trees, puts them into fruit boxes and ships them. He can ship a fruit box if it is full with 20 peaches. If he has less than 20 peaches, he has to pick more peaches so he can fill a fruit box with 20 peaches and ship it.
We would like to help John by writing an automation software that initiates the filling and shipping of boxes. We get the number of peaches from John, and we print a message for each group of 20 peaches and say how many peaches have been shipped so far. We print "shipped 60 peaches so far" for the third box, for example. We would like to do this with a for loop. We do not need to worry about the peaches leftover. To achieve this, perform the following steps:
- Create a new class and enter PeachBoxCounter as the class name
- Import the java.util.Scanner package:
- In the main() use System.out.print to ask the user for the numberOfPeaches.
- Write a for loop that counts the peaches that are shipped so far. This starts from zero, increases 20 by 20 until the peaches left is less than 20.
- In the for loop, print the number of peaches shipped so far.
- Run the main program.
The output should be similar to:
Enter the number of peaches picked: 42
shipped 0 peaches so far
shipped 20 peaches so far
shipped 40 peaches so far
Note
The solution for this activity can be found on page 310.
All three sections of the for loop are optional. This implies that the line for( ; ;) will provide any error. It just provides an invite loop.
This for loop doesn't do anything and won't terminate. Variables declared in the for loop declaration are available in the statements of the for loop. For example, in our first example, we printed the value of i from the statements sections because the variable i was declared in the for loop. This variable is, however, not available after the for loop and can be freely declared. It can't however be declared inside the for loop again:
for (int i = 0; i <= 9; i++)
int i = 10; //Error, i is already declared
For loops can also have braces enclosing the statements if we have more than one statement. This is just as we discussed in the if-else statements earlier. If we have only one statement, then we don't need to have braces. When the statements are more than one, they need to be enclosed within braces. In the following example, we are printing out the value of i and j:
for (int i = 0, j = 0; i <= 9; i++, j++) {
System.out.println(i);
System.out.println(j);
}
Note
The expressions must be valid Java expressions, that is, expressions that can be terminated by a semicolon.
A break statement can be used to interrupt the for loop and break out of the loop. It takes the execution outside the for loop.
For example, we might wish to terminate the for loop we created earlier if i is equal to 5:
for (int i = 0; i <= 9; i++){
if (i == 5)
break;
System.out.println(i);
}
Output:
0
1
2
3
4
The preceding for loop iterates from 0, 1, 2, and 3 and terminates at 4. This is because after the condition i, that is, 5 is met, the break statement is executed, which ends the for loop and the statements after it are not executed. Execution continues outside the loop.
The continue statement is used to tell the loop to skip all the other statements after it and continue execution to the next iteration:
for (int i = 0; i <= 9; i++){
if (i == 5)
continue;
System.out.println(i);
}
Output:
0
1
2
3
4
6
7
8
9
The number 5 is not printed because once the continue statement is encountered, the rest of the statements after it are ignored, and the next iteration is started. The continue statements can be useful when there are a few exceptions you wish to skip when processing multiple items.
Nested for Loops
The block of statements within a loop can be another loop was well. Such constructs are known as nested loops:
public class Nested{
public static void main(String []args){
for(int i = 1; i <= 3; i++) {
//Nested loop
for(int j = 1; j <= 3; j++) {
System.out.print(i + "" + j);
System.out.print("\t");
}
System.out.println();
}
}
}
Output:
11 12 13
21 22 23
31 32 33
For each single loop of i, we loop j three times. You can think of these for loops as follows:
Repeat i three times and for each repetition, repeat j three times. That way, we have a total of 9 iterations of j. For each iteration of j, we then print out the value of i and j.
Exercise 9: Implementing a Nested for Loop
Our goal in this exercise is to print a pyramid of * with seven rows, like so:

Figure 3.1: Pyramid of * with seven rows
To achieve this goal, perform the following steps:
- Right-click the src folder and select New | Class.
- Enter NestedPattern as the class name, and then click OK.
- In the main method, create a for loop that initializes the variable i at 1, introduces the condition so that the value of i is at most 15, and increments the value of i by 2:
public class NestedPattern{
public static void main(String[] args) {
for (int i = 1; i <= 15; i += 2) {
}
}
}
}
- Within this loop, create two more for loops, one to print the spaces and the other to print the *:
for (int k = 0; k < (7 - i / 2); k++) {
System.out.print(" ");
}
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
- Within the outer for loop, add the following code to add the next line:
System.out.println();
Run the program. You will see the resultant pyramid.
for-each Loops
for each loops are an advanced version of for loops that were introduced in Java 5. They are used to perform a given operation on every item in an array or list of items.
Let's take a look at this for loop:
int[] arr = { 1, 2, 3, 4, 5 , 6, 7, 8, 9,10};
for (int i = 0; i < 10; i++){
System.out.println(arr[i]);
}
The first line declares an array of integers. An array is a collection of items of the same type. In this case, the variable arr is holding a collection of 10 integers. We then use a for loop from 0 to 10, printing the elements of this array. We are using i < 10 because the last item is at index 9, not 10. This is because the elements of an array start with index 0. The first element is at index 0, the second at index 1, the third at 2, and so on. arr[0] will return the first element, arr[1] the second, arr[2] the third, and so on.
This for loop can be replaced with a shorter for each loop. The syntax of a for each loop is as follows:
for( type item : array_or_collection){
//Code to executed for each item in the array or collection
}
For our preceding example, the for each loop would be as follows:
for(int item : arr){
System.out.println(item);
}
int item is the current element in the array we are at. The for each loop will iterate for all the elements in the array. Inside the braces, we print out the item. Note that we didn't have to use arr[i] like in the for loop earlier. This is because the for each loop automatically extracts the value for us. In addition, we didn't have to use an extra int i to keep the current index and check if we are below 10 (i < 10), like in the for loop we used earlier. for each loops are shorter and automatically check the range for us.
For example, we can use the for each loop to print the squares of all the elements present in the array, arr:
for(int item : arr){
int square = item * item;
System.out.println(square);
}
Output:
1
4
9
16
25
36
49
64
81
10
The while and do while Loops
Sometimes, we wish to execute certain statements repeatedly, that is, as long as a certain Boolean condition is true. Such cases require us to use a while loop or a do while loop. A while loop first checks a Boolean statement and executes a block of code if the Boolean is true, otherwise it skips the while block. A do while loop first executes a block of code once before it checks the Boolean condition. Use a do while loop when you want the code to be executed at least once and a while loop when you want the Boolean condition to be checked first before the first execution. The following are the formats of the while and do while loops:
The syntax for the while loop:
while(condition) {
//Do something
}
The syntax for the do while loop:
do {
//Do something
}
while(condition);
For example, to print all of the numbers from 0 to 10 using a while loop, we would use the following code:
public class Loops {
public static void main(String[] args){
int number = 0;
while (number <= 10){
System.out.println(number);
number++;
}
}
}
Output:
0
1
2
3
4
5
6
7
8
9
10
We could also write the preceding code using a do while loop:
public class Loops {
public static void main(String[] args){
int number = 0;
do {
System.out.println(number);
number++;
}while (number <= 10);
}
}
With the do while loop, the condition is evaluated last, so we are sure that the statements will be executed at least once.
Exercise 10: Implementing the while Loop
To print the first 10 numbers in the Fibonacci series using the while loop, perform the following steps:
- Right-click the src folder and select New | Class.
- Enter FibonacciSeries as the class name, and then click OK.
- Declare the variables that are required in the main method:
public class FibonacciSeries {
public static void main(String[] args) {
int i = 1, x = 0, y = 1, sum=0;
}
}
Here, i is the counter, x and y store the first two numbers of the Fibonacci series, and sum is a variable that is used to calculate the sum of the variables x and y.
- Implement a while loop with the condition so that the counter i does not go beyond 10:
while (i <= 10)
{
}
- Within the while loop, implement the logic to print the value of x, and then assign the appropriate values to x, y, and sum so that we are always printing the sum of the last and the penultimate number:
System.out.print(x + " ");
sum = x + y;
x = y;
y = sum;
i++;
Activity 9: Implementing the while Loop
Remember John, who is a peach grower. He picks peaches from his trees, puts them into fruit boxes and ships them. He can ship a fruit box if it is full with 20 peaches. If he has less than 20 peaches, he has to pick more peaches so he can fill a fruit box with 20 peaches and ship it.
We would like to help John by writing an automation software that initiates the filling and shipping of boxes. We get the number of peaches from John, and we print a message for each group of 20 peaches and say how many boxes we have shipped and how many peaches we have left, e.g., "2 boxes shipped, 54 peaches remaining". We would like to do this with a while loop. The loop will continue as we have a number of peaches that would fit at least one box. In contrast to the previous activity with for, we will also keep track of the remaining peaches. To achieve this, perform the following steps:
- Create a new class and enter PeachBoxCounter as the class name
- Import the java.util.Scanner package:
- In the main() use System.out.print to ask the user for the numberOfPeaches.
- Create a numberOfBoxesShipped variable.
- Write a while loop that continues as we have at least 20 peaches.
- In the loop, remove 20 peaches from numberOfPeaches and increment numberOfBoxesShipped by 1. Print these values.
- Run the main program.
The output should be similar to:
Enter the number of peaches picked: 42
1 boxes shipped, 22 peaches remaining
2 boxes shipped, 2 peaches remaining
Note
The solution for this activity can be found on page 311.
Activity 10: Implementing Looping Constructs
Our goal is to create a ticketing system so that when the user puts in a request for the tickets, the tickets are approved based on the number of seats remaining in the restaurant.
To create such a program, perform the following steps:
- Import the packages that are required to read data from the user.
- Declare the variables to store the total number of seats available, remaining seats, and tickets requested.
- Within a while loop, implement the if else loop that checks whether the request is valid, which implies that the number of tickets requested is less than the number of seats remaining.
- If the logic in the previous step is true, then print a message to denote that the ticket is processed, set the remaining seats to the appropriate value, and ask for the next set of tickets.
- If the logic in step 3 is false, then print an appropriate message and break out of the loop.
Note
The solution for this activity can be found on page 312.
Activity 11: Continuous Peach Shipment with Nested Loops.
Remember John, who is a peach grower. He picks peaches from his trees, puts them into fruit boxes and ships them. He can ship a fruit box if it is full with 20 peaches. If he has less than 20 peaches, he has to pick more peaches so he can fill a fruit box with 20 peaches and ship it.
We would like to help John by writing an automation software that initiates the filling and shipping of boxes. In this new version of our automation software, we will let John bring in the peaches in batches of his own choosing and will use the remaining peaches from the previous batch together with the new batch.
We get the incoming number of peaches from John and add it to the current number of peaches. Then, we print a message for each group of 20 peaches and say how many boxes we have shipped and how many peaches we have left, e.g., "2 boxes shipped, 54 peaches remaining". We would like to do this with a while loop. The loop will continue as we have a number of peaches that would fit at least one box. We will have another while loop that gets the next batch and quits if there is none. To achieve this, perform the following steps:
- Create a new class and enter PeachBoxCount as the class name
- Import the java.util.Scanner package:
- Create a numberOfBoxesShipped variable and a numberOfPeaches variable.
- In the main(), write an infinite while loop.
- Use System.out.print to ask the user for the incomingNumberOfPeaches. If this is zero, break out of this infinite loop.
- Add the incoming peaches to the existing peaches.
- Write a while loop that continues as we have at least 20 peaches.
- In the for loop, remove 20 peaches from numberOfPeaches and increment numberOfBoxesShipped by 1. Print these values.
- Run the main program.
The output should be similar to:
Enter the number of peaches picked: 23
1 boxes shipped, 3 peaches remaining
Enter the number of peaches picked: 59
2 boxes shipped, 42 peaches remaining
3 boxes shipped, 22 peaches remaining
4 boxes shipped, 2 peaches remaining
Enter the number of peaches picked: 0
Note
The solution for this activity can be found on page 313.
- Spring 5.0 By Example
- Spring 5企業(yè)級(jí)開發(fā)實(shí)戰(zhàn)
- PHP 從入門到項(xiàng)目實(shí)踐(超值版)
- Go語(yǔ)言高效編程:原理、可觀測(cè)性與優(yōu)化
- The Computer Vision Workshop
- Magento 1.8 Development Cookbook
- SharePoint Development with the SharePoint Framework
- 批調(diào)度與網(wǎng)絡(luò)問(wèn)題的組合算法
- 基于ARM Cortex-M4F內(nèi)核的MSP432 MCU開發(fā)實(shí)踐
- AutoCAD 2009實(shí)訓(xùn)指導(dǎo)
- 石墨烯改性塑料
- Python預(yù)測(cè)分析與機(jī)器學(xué)習(xí)
- Python Social Media Analytics
- Python 3快速入門與實(shí)戰(zhàn)
- Mastering ASP.NET Core 2.0