--- description: In this lab, we are going to explore loops more, as you've already learned how to write while-loop and for-loop, and finally, we will talk about reading text files. --- <h1 style='border: none'><center>Programming I Lab 5</center></h1> <h2 style='border: none'><center>Loops & Loops & Loops ...</center></h2> <h5><center>The Islamic University of Gaza<br>Engineering Faculty<br>Department of Computer Engineering</center></h5> <h6>Author: Mohammed Nafiz ALMadhoun<span style="float:right">2021/10/22</span></h6> --- <p style='text-align:justify'> In this lab, we are going to explore loops more, as you've already learned how to write while-loop and for-loop, and finally, we will talk about reading text files. </p> ## Lab Objectives - Be able to write while, for, and do-while loops. - Be able to use `continue`, and `break` statements. - Be able to read text files. - Be able to write text files. ## Loops ### While loop <p style='text-align: justify'> The while loop is the most basic syntax for a loop, the body of the loop will be executed as long as the condition is `true`. </p> ```java= while (condition) { // statments } ``` The condition will be a boolean expression <div style="page-break-after: always;"></div> ### For loop <p style='text-align: justify'> The syntax in for loop makes it easier to loop on countable things, for example, if we want to loop through all the characters in a string we can write. </p> ```java= String test = "This is a test!"; int length = test.length(); for (int i=0; i<length; i++){ System.out.println(test.charAt(i)); } ``` Return to the previous lab to understand the syntax! ### Do-While loop <p style='text-align: justify'> The do-while syntax allows you to execute one iteration of the loop without checking the condition, this could be very useful if the condition depends on the user input, for example, we could write the summation program as follows: </p> ```java= public static void main(String[] args){ Scanner input = new Scanner(System.in); int sum = 0; int x = 0; // Note that x = 0, so x != 0 is false! do { System.out.print("Enter a number, or 0 to exit: "); x = input.nextInt(); sum += x; } while (x != 0); System.out.printf("Sum = %d%n", sum); } ``` <div style="page-break-after: always;"></div> ### Break statement <p style='text-align: justify'> The break statement let you break, it will be very useful if you have a complex loop condition, for example, we could write the previous program using while as following: </p> ```java= public static void main(String[] args){ Scanner input = new Scanner(System.in); int sum = 0; while (true) { System.out.print("Enter a number, or 0 to exit: "); int x = input.nextInt(); if (x == 0) break; sum += x; } System.out.printf("Sum = %d%n", sum); } ``` As you've noted that the while condition is `true`, which mean the loop will go forever, but in the loop body we have an if statement that break `if x==0`, so the loop will be broken if the condition is `true`. Note that `sum += x` will not be executed. ### Continue statment <p style='text-align: justify'> The continue statement let us continue to the next iteration without executing the following statements of the current iteration. </p> ```java= public static void main(String[] args){ for (int i=0;i<10;i++){ if (i % 3 == 0) continue; System.out.println(i); } } ``` This code will print all the numbers that are not divided by `3`, because if the number is divided by 3, the condition will be `true`, and we will execute the `continue` statement that will continue to the next iteration. <div style="page-break-after: always;"></div> ## Extra: Text Files In this section, we are going to learn how to read, write to text files. ### Reading text file To read a file, we will use the Scanner class, a Scanner object could be constructed using a file, we could create a file object using File class, which is located in `java.io.File`. ```java= import java.util.Scanner; import java.io.File; public class Test { public static void main(String[] args) throws Exception { File testFile = new File("test.txt"); Scanner fileInput = new Scanner (testFile); while (fileInput.hasNext()) { System.out.println(fileInput.nextLine()); } } } ``` Note that we've imported the File class, and added `throws Exception`, this will let java know that there are some errors that could happen and we didn't handle them (e.g file not found!) This code will print all the content of a text file. Look at the File docs here: https://docs.oracle.com/javase/8/docs/api/java/io/File.html ### Writing to a text file To write to file, we will use `PrintWriter`, which could be constructed using the file path, then we will use the methods in the docs to write our text file. Look at the docs here: https://docs.oracle.com/javase/8/docs/api/java/io/PrintWriter.html ```java= import java.util.Scanner; import java.io.PrintWriter; public class Test { public static void main(String[] args) throws Exception { PrintWriter testWriter = new PrintWriter("newFile.txt"); for (int i=0;i<2;i++){ testWriter.println(i); } testWriter.close(); } } ``` Note that we've used `close()` method at the end of our program, without changes will not be saved! ## Lap Tasks ### Task 1: Count the words. In this program, you should ask the user to enter a filename, then you should print the number of words in this file. <center> ![Task 1 Expected Output.](https://i.imgur.com/OkuBXE1.png =550x) Task 1 Expected Output. </center> ### Task 2: Twinkle Twinkle. Using loops, print the following pattern of stars. <center> ![Task 2 Expected Ouput](https://i.imgur.com/UYpofxN.png =550x) Task 2 Expected Ouput </center> <center>Good luck in your midterm exams ❤</center> ###### tags: `Programming` `Java` `IUG` <center>End Of Lab 5</center>