250 likes | 268 Vues
Comprehensive guide to loops in Java, covering while, do-while, and for loops. Learn to generate random numbers and use increment and decrement operators effectively. Includes examples and explanation of loop structures.
E N D
Chapter 4:Loops and Files Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis This slide show consists of excerpts from the orginal Chapter 4 slide set.
Chapter Topics Chapter 4 discusses the following main topics: A few preliminary topics Generating Random Numbers with the Random class The Increment and Decrement Operators Loops in java The while Loop The do-while Loop The for Loop
Generating Random Numbers with the Random Class Some applications, such as games and simulations, require the use of randomly generated numbers. A simple example is the “I’m thinking of number between 1 and 10”, (or some other variation), where the program must generate a random number between 1 and 10 for the user to guess. The program reads the user’s guess and then tells them if they are right or not. For such programs, the Java API has a class named Random, that provides a method to use for generating random numbers.
Generating Random Numbers with the Random Class To use the Random class, you would first include the import statement: import java.util.Random; And secondly, instantiate a object of the Random class: Random ran = new Random(); After that is done, anytime your program needs random number, you can call a method depending on what type of number you need.
Generating Random Numbers with the Random Class For example: To obtain an integer, use: int randomInt = ran.nextInt(); To obtain an integer within a specific range, use: int randomInt = ran.nextInt(11); // returns an int from 0 to 10
Some Methods of the Random Class See example: RollDice.java
The Increment and Decrement Operators • In many of the programs that use loops, you will see the use of two operators that you may not have encountered yet. • They are: • Incrementation operator ++ • Decrementation operator -- Let’s take a look at the meaning of these operators before reading the sample codes of chapter 4.
The Increment and Decrement Operators Here Increment means add 1 and decrement means subtract 1. There are numerous times where a variable must simply be incremented or decremented. number = number + 1; number = number – 1; Java provide shortened ways to increment and decrement a variable’s value. Using the ++ or -- unary operators, this task can be completed quickly. number++; or ++number; number--; or --number; There is an Example Program in the Chapter 4 Source Code folder online named: IncrementDecrement.java A version of that follows on the next page.
/** This program demonstrates the ++ and -- operators. */ public class IncrementDecrement2 { public static void main(String[] args) { int number = 4; // number starts out with 4 System.out.println("number starts out at " + number); number++; // Increment number. System.out.println(" After incrementation number is " + number); number--; // Decrement number. System.out.println(" After decrementation number is " + number); } } OUTPUT number starts out at 4 After incrementation number is 5 After decrementation number is 4
Loops Frequently in programming, you want certain segments of code to be repeated without having to write the same code multiple times. In programming, a loop is a statement that will cause a segment of code to be repeated (i.e. iterated). For example, think back to Project 1 where you calculated the BMI for 5 persons. Recall that the same code that worked for 1 person had to be written 4 more times. By using a looping statement, we could have written this code segment once and then placed in a looping construct and specify that it be repeated 5 times.
Loops Java provides three different looping structures. The while loop The do-while loop The for loop
The while Loop Java provides three different looping structures. The while loop has the form: while(condition) { statement1; statement2; … } While the condition is true, the statements will execute repeatedly. The while loop is a pretest loop, which means that it will test the value of the condition prior to executing the loop.
The while loop Flowchart true boolean expression? Statement1; Statement2; … false
The while Loop Care must be taken to set the condition to false somewhere in the loop so the loop will end. Loops that do not end are called infinite loops. A while loop executes 0 or more times. If the condition is false, the loop will not execute. Example: WhileLoop.java
Infinite Loops In order for a while loop to end, the condition must become false. The following loop will not end: int x = 20; while(x > 0) { System.out.println("x is greater than 0"); } The variable x never gets decremented so it will always be greater than 0. Adding the x-- above fixes the problem.
Infinite Loops This version of the loop decrements x during each iteration: int x = 20; while(x > 0) { System.out.println("x is greater than 0"); x--; }
Block Statements in Loops Curly braces are required to enclose block statement while loops. (like block if statements) while (condition) { statement; statement; statement; }
The do-while Loop The do-while loop is a post-test loop, which means it will execute the loop prior to testing the condition. The do-while loop (sometimes called called a do loop) takes the form: do { statement(s); }while (condition); Example: TestAverage1.java
The do-while Loop Flowchart statement(s) true boolean expression? false
The for Loop The for loop is a pre-test loop. The for loop allows the programmer to initialize a control variable, test a condition, and modify the control variable all in one line of code. The for loop takes the form: for(initialization; test; update) { statement(s); } See example: Squares.java
The for Loop Flowchart true boolean expression? statement(s) update false
The Sections of The for Loop The initialization section of the for loop allows the loop to initialize its own control variable. The test section of the for statement acts in the same manner as the condition section of a while loop. The update section of the for loop is the last thing to execute at the end of each loop. Example: UserSquares.java
The for Loop Initialization The initialization section of a for loop is optional; however, it is usually provided. Typically, for loops initialize a counter variable that will be tested by the test section of the loop and updated by the update section. The initialization section can initialize multiple variables. Variables declared in this section have scope only for the for loop.
The Update Expression The update expression is usually used to increment or decrement the counter variable(s) declared in the initialization section of the for loop. The update section of the loop executes last in the loop. The update section may update multiple variables. Each variable updated is executed as if it were on a line by itself.
When to use each type of loop… Page 233 The while loop is a pre-test loop ideal for cases where where you do not want the loop to iterate if the condition is false from the beginning. The do-while loop is a post-test loop and is used in situations where you always want the loop to iterate at least once. The for loop is a pretest loop that is used for simple counting loops, ideal when the exact number of iterations is known or can be calculated before the loop begins.