Our code right now is growing in terms of lines of code ~100 lines of code and 30-40 % of that code is repetition, so we need a mechanism that allows us to “repeat” several statements.
Java provides two types of loop
There are two types of loops:
Pre-test: you check for a true statement BEFORE performing an action
Post-test: you check for a true statement AFTER performing an action
Regardless of the type of loops, we need to understand that there are four elements that every loop shall have.
Elements of a loop
All loops contain the following four components:
1. Initialization of the control variable. This variable will keep track of the times/state of the mechanism to keep the loop running
2. A Boolean condition, a.k.a., test/check. This condition will “check” if the Boolean statements remain true; if that is true, then the loop will continue; otherwise (i.e., false), the loop will stop. Remember that we can use relational operators to extract a Boolean expression.
3. The body of the loop. This is the set of commands that are redundant in a code and we wish to repeat in the loop.
4. The update of the control variable. The update can be by incrementing/decrementing the control variable in order to accomplish the Boolean condition of the check. The control variable works as an accumulator that will keep track of the current value before reaching a Boolean condition.
It is common to have different ways to update your control variable. For example,
counter = counter + 1;
This means that for the old counter (to the right side of the equals) you add 1 to it, and then assign the new counter. There is also a shortcut to do this:
counter += 1;
This way counter will be updated by the old counter plus 1.
There is another shortcut for this particular update using the ++ operators. Notice that the ++ operator will only modify the control variable by one. We can use counter++; to have the same result.
Shortcut:
counter = counter + 1;
counter++;
counter += 1;
Ask someone to say the word “hello”:
3 times
5 times
7 times
13 times
What did you think when you needed to count up to 13?
Repeating “hello” 3 times was probably not a big deal. Maybe 5 not too much. But 7 or maybe 13 will require some kind of counting either with your fingers or with something else.
Your fingers become sort of a counter, and now you could potentially think:
If the counter == 13, then I will stop repeating the word “hello”
As long as the counter <= 13, I will repeat the word “hello.”
As long the counter != 13, I will repeat the word “hello,” then I will stop
Once I arrive to counter == 14, I will not say “hello” and stop
Types of Loops
Java supports two types of loops: pre-test and post-test. The pre-test loops are:
The while loop
The for loop
The pre-test checks if the test of the loop is true in order to execute the body of a loop. Otherwise, the loop will not be executed.
The post-order loop is:
do-while
The post-test performs an action as part of the body, and then it checks if the condition is true.
The while loop is a pre-test loop that will allow us to repeat certain statements in the following format:
// (1)
while( (2) ){
... (3)
... (4)
}
Example 1: Write a program that prints the string “hello” five times.
1. int counter = 0; //(1)
2. while(counter < 0) //(2)
3. {
4. System.out.println("hello"); //(3)
5. counter = counter + 2; //(4) counter++;
6. }
The for loop is equivalent to the while loop; both of them are pre-test loops. The difference is that the for-loop uses a compact way to store information and has a different execution order.
The for loop is a more compressed way to use a loop. It allows us to perform exactly the same as the while loop. The format of the for-loop is as follows:
for((1) ; (2); (4)){
(3)
}
The order of execution of the for-loop is the initialization, then the test, followed by the body, and finally the update. After that, we repeat (2), and in case the test is true, then (3) and (4) are run. In case step (2) is false, that indicates to get out of the loop execution.
You can get away with not incorporating the {} IF there is only one statement in the body of the loop.
Example 1: Write a program that prints the string “hello” five times.
// (1) (2) (4)
for(int counter = 0; counter < 0; counter++){
System.out.println("hello"); // (3)
}
The do-while loop is a post-fix loop that allows us to perform some repetitive action and then check if a condition is held. The format of the do-while loop is as follows:
// (1)
do{
// (3)
// (4)
}while((2));
Example 1: Write a program that prints the string “hello” five times.
int counter = 0; // (1)
do{
System.out.println("hello"); // (3)
counter++; // (4)
}while(counter < 0);
The importance of data security allows us to restrict the user from providing invalid input. In order to avoid a problem or a “bug” in the software, you must restrict the user’s input with some interval of possible values
Example: Write a program that asks the user to enter a value between 0-5. If the user provides you with invalid input, your program shall run again until the user satisfies the request.
· Selection of loop: Do-while, since we will ask for the user’s input first
· What is the condition:
While input < 0 || input > 5
While input >= 0 && input <= 5
You have three options to validate user input:
Option #1 Validating by flipping the logic (post-test)
int x;
do{
System.out.println("Enter a number [0,5]");
x = input.nextInt();
}while(x < 0 || x > 5);
System.out.println("Thank you");
Option #2: Sentinel or Flags
int n;
boolean sentinel = true;
while(sentinel)
{
System.out.println("Please enter a value between 0 and 5");
n = input.nextInt();
if(n >= 0 && n <= 5)
sentinel = false;
}
System.out.println("Thank you for entering the correct value");
Option #3: Making an infinite loop and use the break “emergency exit”
while(true)
{
System.out.println("Please enter a value between 0 and 5");
int n = input.nextInt();
if(n >= 0 && n <= 5){
break;
}
}
System.out.println("Thank you for entering the correct value");
Write a program that generates the following pattern:
1
12
123
1234
12345
Notice the following:
The program generates rows (lines)
The program generates columns (number of numbers)
For every row, it prints the corresponding numeric number, e.g., first row prints 1, second row prints 2, …, n row will print n, where n is any number.
Every time we have multiple variables that depend on each other, we need to consider the potential nested loop. A nested loop is a loop within another loop. In this case, let's create variables for the rows and columns
for(int row = 1; row <= 5; row++){
for(int col = 1; col <=row; col++){
System.out.print(col);
}
System.out.println();
}
When you process a file, there are a couple of new things you need to incorporate into the code:
Import the library that handles the input processing: import java.io.*
Handle the potential errors in case the file is not found: throws IOException
Select the mechanism to handle the file:
Reading a file: Scanner(new File(“nameoffile.txt”));
Writing a file: PrintWriter(new File(“nameOfFile.txt”));
User interaction eventually becomes more "effective" if data is provided through files or different forms of storage (e.g., cloud files, links to websites, database queries). Most of the data that computer programmers will manage are stored in data files such as text files (.txt), Microsoft files (docx, xlsx), spreadsheets, and others.
Reading files in Java requires to use of an additional library to handle input/output processes.
import java.io.*
it also requires a mechanism to handle potential problems (i.e., exceptions) that might happen to files that are an attempt to read or write. For example, if the file is not there, or the file is there but is corrupted, or someone else is using it. There are several potential exceptions that might occur while reading or writing a file. That is why it is important to use the following line of code just after the main declaration:
throws IOException
This way in case something "bad" happens, it can be handled by java properly.
The following piece of code ReadFileExample.java demonstrates a simple program that reads a file named "test.txt" that is in the same working directory as ReadFileExample.java. The program will read the content (line by line) of the file and print each line on the screen.
import java.util.Scanner;
import java.io.*;
public class ReadFileExample{
public static void main(String [] args)throws IOException{
Scanner input = new Scanner(new File("test.txt"));
while(input.hasNext()){
String line = input.nextLine();
System.out.println(line);
}
}
}
*Make sure your file is in the same directory as your program
import java.util.Scanner;
import java.io.*;
public class WriteFileExample{
public static void main(String [] args)throws IOException{
PrintWriter pr = new PrintWriter("output.txt");
pr.println("this is a TEST!");
pr.close();
}
}
Task: Write a program that reads a file called “poetry.txt” and then counts the total number of vowels in the file. The program shall report back into a file called “output.txt” the total number of vowels found in the file poetry.txt as follows:
Total ‘a’ in file: #
Total ‘e’ in file: #
Total ‘i’ in file: #
Total ‘o’ in file: #
Total ‘u’ in file: #
How to generate a random number
Make sure your file is in the same directory as your program
(int)(Math.random()*11)
> e.g., 8