Download presentation
Presentation is loading. Please wait.
Published byOscar Roberts Modified over 9 years ago
1
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 01321308071 Chapter 4 Loops
2
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 01321308072 Objectives F To write programs for executing statements repeatedly using a while loop (§4.2). F To develop a program for GuessNumber and SubtractionQuizLoop (§4.2.1). F To follow the loop design strategy to develop loops (§4.2.2). F To develop a program for SubtractionQuizLoop (§4.2.3). F To control a loop with a sentinel value (§4.2.3). F To obtain large input from a file using input redirection rather than typing from the keyboard (§4.2.4). F To write loops using do-while statements (§4.3). F To write loops using for statements (§4.4). F To discover the similarities and differences of three types of loop statements (§4.5). F To write nested loops (§4.6). F To learn the techniques for minimizing numerical errors (§4.7). F To learn loops from a variety of examples (GCD, FutureTuition, MonteCarloSimulation) (§4.8). F To implement program control with break and continue (§4.9). F (GUI) To control a loop with a confirmation dialog (§4.10).
3
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 3 Motivations Suppose that you need to print a string (e.g., "Welcome to Java!") a hundred times. It would be tedious to have to write the following statement a hundred times: System.out.println("Welcome to Java!"); So, how do you solve this problem?
4
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Java Loops – while, do…While, & for 4 There may be a situation when we need to execute a block of code several number of times, and is often referred to as a loop. Java has very flexible three looping mechanisms. You can use one of the following three loops: while Loop do...while Loop for Loop
5
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 5 Opening Problem System.out.println("Welcome to Java!"); … System.out.println("Welcome to Java!"); Problem: 100 times
6
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 6 while Loop pseudocode syntax while Java syntax while ( ) { } Use a loop statement if you need to do the same thing repeatedly. The condition is at the bottom of the loop (in contrast to the while loop, where the condition is at the top of the loop). The compiler requires putting a ";" at the very end, after the do loop's condition. Proper style dictates putting the "while" part on the same line as the " } "
7
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 7 while Loop Flow Chart while (loop-continuation-condition) { // loop-body; Statement(s); } // end of while int count = 0; while (count < 100) { System.out.println("Welcome to Java!"); count++; } // end of while
8
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 8 while Loop int count = 0; while (count < 100) { System.out.println("Welcome to Java"); count++; } // end of while A while loop is a control structure that allows you to repeat a task a certain number of times. Using loop statement means tell the computer to print a string a hundred times without coding: public class Welcome { public static void main (String [ ] args){ int count = 0; while (count < 100) { System.out.println("Welcome to Java"); count++; } // end of while } // end of main method } // end of class
9
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 9 Here key point of the while loop is that the loop might not ever run. When the expression is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed. Syntax while(Boolean_expression) { //Statements } Example: public class Test1 { public static void main(String args[]){ int x= 10; while( x < 20 ){ System.out.print("value of x :" + x); x++; System.out.print("\n"); } //end of while } // end of main } //end of class
10
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 while Loop Write a main method that finds the sum of user- entered integers where -99999 is a sentinel value. public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); int sum = 0; // sum of user-entered values int x; // a user-entered value System.out.print("Enter an integer (-99999 to quit): "); x = stdIn.nextInt(); while (x != -99999) { sum = sum + x; System.out.print("Enter an integer (-99999 to quit): "); x = stdIn.nextInt(); } // end of while System.out.println("The sum is " + sum); } // end main
11
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 11 import java.util.Scanner; public class SentinelValue { /** Main method */ public static void main(String[] args) { // Create a Scanner Scanner input = new Scanner(System.in); // Read an initial data System.out.print( "Enter an int value (the program exits if the input is 0): "); int data = input.nextInt(); // Keep reading data until the input is 0 int sum = 0; while (data != 0) { sum += data; // Read the next data System.out.print( "Enter an int value (the program exits if the input is 0): "); data = input.nextInt(); } //end of while System.out.println("The sum is " + sum); } //end of main } //end of class Run Enter an int value (the program exits if the input is 0): 2 Enter an int value (the program exits if the input is 0): 3 Enter an int value (the program exits if the input is 0): 4 Enter an int value (the program exits if the input is 0): 0 The sum is 9
12
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 12 Trace while Loop int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } Initialize count animation
13
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 13 Trace while Loop, cont. int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } (count < 2) is true animation
14
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 14 Trace while Loop, cont. int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } Print Welcome to Java animation
15
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 15 Trace while Loop, cont. int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } Increase count by 1 count is 1 now animation
16
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 16 Trace while Loop, cont. int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } (count < 2) is still true since count is 1 animation
17
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 17 Trace while Loop, cont. int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } Print Welcome to Java animation
18
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 18 Trace while Loop, cont. int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } Increase count by 1 count is 2 now animation
19
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 19 Trace while Loop, cont. int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } (count < 2) is false since count is 2 now animation
20
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 20 Trace while Loop int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; } The loop exits. Execute the next statement after the loop. animation
21
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 21 Caution Don’t use floating-point values for equality checking in a loop control. Since floating-point values are approximations for some values, using them could result in imprecise counter values and inaccurate results. Consider the following code for computing 1 + 0.9 + 0.8 +... + 0.1: double item = 1; double sum = 0; while (item != 0) { // No guarantee item will be 0 sum += item; item -= 0.1; } System.out.println(sum); Variable item starts with 1 and is reduced by 0.1 every time the loop body is executed. The loop should terminate when item becomes 0. However, there is no guarantee that item will be exactly 0, because the floating-point arithmetic is approximated. This loop seems OK on the surface, but it is actually an infinite loop.
22
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 22 do-while Loop do { // Loop body; Statement(s); } while (loop-continuation-condition); The do-while loop is a variation of the while loop. The syntax below:
23
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 23 do While Loop When to use a do loop: –If you know that the repeated thing will always have to be done at least one time. F Syntax: do { } while ( ); –Note: The condition is at the bottom of the loop (in contrast to the while loop, where the condition is at the top of the loop). –The compiler requires putting a ";" at the very end, after the do loop's condition. –Proper style dictates putting the "while" part on the same line as the "}"
24
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 The do...while Loop 24 If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the loop execute again. This process repeats until the Boolean expression is false. public class Test2 { public static void main(String args[]){ int x= 10; do { System.out.print("value of x : " + x ); x++; System.out.print("\n"); } while( x < 20 ); } // end of main } //end of class
25
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 25 do while Loop // FloorSpace.java – Calculates total floor space in a house import java.util.Scanner; public class FloorSpace { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); double length, width; // room dimensions double floorSpace = 0; // house's total floor space String response; // user's y/n response do { System.out.print("Enter the length: "); length = stdIn.nextDouble(); System.out.print("Enter the width: "); width = stdIn.nextDouble(); floorSpace += length * width; System.out.print("Any more rooms? (y/n): "); response = stdIn.next(); } while (response.equalsIgnoreCase("y")); System.out.println("The total floor space is " + floorSpace); } // end main } // end class
26
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 26 for Loops for (initial-action; loop- continuation-condition; action-after-each-iteration) { // loop body; Statement(s); } int i; for (i = 0; i < 100; i++) { System.out.println( "Welcome to Java!"); }
27
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 27 for Loop When to use a for loop: –If you know the exact number of loop iterations before the loop begins. For example, use a for loop to: –Print this countdown from 10. Sample session: 10 9 8 7 6 5 4 3 2 1 Liftoff! –Find the factorial of a user-entered number. Sample session: Enter a whole number: 4 4! = 24
28
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 28 for Loop for loop syntax for ( ; ; ) { } for loop example for (int i=10; i>0; i--) { System.out.print(i + " "); } System.out.println("Liftoff!"); for loop semantics: Before the start of the first loop iteration, execute the initialization component. At the top of each loop iteration, evaluate the condition component: If the condition is true, execute the body of the loop. If the condition is false, terminate the loop (jump to the statement below the loop's closing brace). At the bottom of each loop iteration, execute the update component and then jump to the top of the loop.
29
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 29 for Loop F Trace this code fragment with an input value of 3. Scanner stdIn = new Scanner(System.in); int number; // user entered number double factorial = 1.0; // factorial of user entry System.out.print("Enter a whole number: "); number = stdIn.nextInt(); for (int i=2; i<=number; i++) { factorial *= i; } System.out.println(number + "! = " + factorial); for loop index variables are often, but not always, named i for “index.” Declare for loop index variables within the for loop heading.
30
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 30 A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. A for loop is useful when you know how many times a task is to be repeated. public class Test3 { public static void main(String args[]) { for(int x = 10; x < 20; x = x+1){ System.out.print("value of x : " + x ); System.out.print("\n"); } //end of for loop } //end of main method } // end of class The for loop
31
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 31 Here is the flow of control in a for loop: The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. for(int x = 10; x<20; x = x + 1); Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. x < 20; // true, then System.out.print("value of x : " + x ); // body of the loop System.out.print("\n"); //body of the for loop // increment the statement and back to checking the condition If it is false, the body of the loop does not execute and flow of control jumps to the next statement past the for loop. After the body of the for loop executes, the flow of control jumps back up to the update statement. The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then update step,then Boolean expression). After the Boolean expression is false, the for loop terminates.
32
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 32 The only thing that can make it faster would be to have less nesting of loops, and looping over less values. The only difference between a for loop and a while loop is the syntax for defining them. There is no performance difference at all. int i = 0; while (i < 20){ // do stuff i++; } Is the same as: for (int i = 0; i < 20; i++){ // do Stuff } ( Actually the for-loop is a little better because the i will be out of scope after the loop while the i will stick around in the while loop case.) A for loop is just a syntactically prettier way of looping For Loop vs. While Loop
33
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 33 Problem: Guessing Numbers Write a program that randomly generates an integer between 0 and 100, inclusive. The program prompts the user to enter a number continuously until the number matches the randomly generated number. For each user input, the program tells the user whether the input is too low or too high, so the user can choose the next input intelligently. Here is a video and sample run: GuessNumber Video Link: Problem Guessing NumbersProblem Guessing Numbers
34
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 34 import java.util.Scanner; public class GuessNumber { public static void main(String[] args) { // Generate a random number to be guessed int number = (int)(Math.random() * 101); // static double, random() Returns a double value with a positive sign, greater than or Scanner input = new Scanner(System.in); // scanner breakdown formatting/allocate input and their data type System.out.println("Guess a magic number between 0 and 100"); int guess = -1; while (guess != number) { // Prompt the user to guess the number System.out.print("\nEnter your guess: "); guess = input.nextInt(); if (guess == number) System.out.println("Yes, the number is " + number); else if (guess > number) System.out.println("Your guess is too high"); else System.out.println("Your guess is too low"); } // End of loop } }
35
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 35 Problem: An Advanced Math Learning Tool The Math subtraction learning tool program generates just one question for each run. You can use a loop to generate questions repeatedly. This example gives a program that generates five questions and reports the number of the correct answers after a student answers all five questions. Video Link: Problem SubtractionQuizLoopProblem SubtractionQuizLoop
36
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 36 import java.util.Scanner; public class SubtractionQuizLoop { public static void main(String[] args) { final int NUMBER_OF_QUESTIONS = 5; // Number of questions int correctCount = 0; // Count the number of correct answers int count = 0; // Count the number of questions long startTime = System.currentTimeMillis(); String output = ""; // output string is initially empty Scanner input = new Scanner(System.in); while (count < NUMBER_OF_QUESTIONS) { // 1. Generate two random single-digit integers int number1 = (int)(Math.random() * 10); int number2 = (int)(Math.random() * 10); // 2. If number1 < number2, swap number1 with number2 if (number1 < number2) { int temp = number1; number1 = number2; number2 = temp; } // 3. Prompt the student to answer “What is number1 – number2?” System.out.print( "What is " + number1 + " - " + number2 + "? "); int answer = input.nextInt(); // 4. Grade the answer and display the result if (number1 - number2 == answer) { System.out.println("You are correct!"); correctCount++; } else System.out.println("Your answer is wrong.\n" + number1 + " - " + number2 + " should be " + (number1 - number2)); // Increase the count count++; output += "\n" + number1 + "-" + number2 + "=" + answer + ((number1 - number2 == answer) ? " correct" : " wrong"); } long endTime = System.currentTimeMillis(); long testTime = endTime - startTime; System.out.println("Correct count is " + correctCount + "\nTest time is " + testTime / 1000 + " seconds\n" + output); } } SubtractionQuizLoop
37
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 37 Ending a Loop with a Sentinel Value Another technique for lop control is to designate a special value. Often the number of times a loop is executed is not predetermined. You may use an input value to signify the end of the loop. Such a special input values is known as a sentinel value. Write a program that reads and calculates the sum of an unspecified number of integers. The input 0 signifies the end of the input. SentinelValue
38
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 38 Trace for Loop int i; for (i = 0; i < 2; i++) { System.out.println( "Welcome to Java!"); } Declare i animation
39
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 39 Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { System.out.println( "Welcome to Java!"); } Execute initializer i is now 0 animation
40
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 40 Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { System.out.println( "Welcome to Java!"); } (i < 2) is true since i is 0 animation
41
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 41 Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); } Print Welcome to Java animation
42
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 42 Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); } Execute adjustment statement i now is 1 animation
43
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 43 Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); } (i < 2) is still true since i is 1 animation
44
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 44 Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); } Print Welcome to Java animation
45
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 45 Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); } Execute adjustment statement i now is 2 animation
46
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 46 Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); } (i < 2) is false since i is 2 animation
47
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 47 Trace for Loop, cont. int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); } Exit the loop. Execute the next statement after the loop animation
48
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 48 Note The initial-action in a for loop can be a list of zero or more comma-separated expressions. The action-after-each- iteration in a for loop can be a list of zero or more comma- separated statements. Therefore, the following two for loops are correct. They are rarely used in practice, however. for (int i = 1; i < 100; System.out.println(i++)); for (int i = 0, j = 0; (i + j < 10); i++, j++) { // Do something }
49
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 49 Note If the loop-continuation-condition in a for loop is omitted, it is implicitly true. Thus the statement given below in (a), which is an infinite loop, is correct. Nevertheless, it is better to use the equivalent loop in (b) to avoid confusion:
50
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 50 Caution Adding a semicolon at the end of the for clause before the loop body is a common mistake, as shown below: Logic Error for (int i=0; i<10; i++); { System.out.println("i is " + i); }
51
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 51 Caution, cont. Similarly, the following loop is also wrong: int i=0; while (i < 10); { System.out.println("i is " + i); i++; } In the case of the do loop, the following semicolon is needed to end the loop. int i=0; do { System.out.println("i is " + i); i++; } while (i<10); Logic Error Correct
52
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 52 The only thing that can make it faster would be to have less nesting of loops, and looping over less values. The only difference between a for loop and a while loop is the syntax for defining them. There is no performance difference at all. int i = 0; while (i < 20){ // do stuff i++; } Is the same as: for (int i = 0; i < 20; i++){ // do Stuff } ( Actually the for-loop is a little better because the i will be out of scope after the loop while the i will stick around in the while loop case.) A for loop is just a syntactically prettier way of looping For Loop vs. While Loop
53
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 53 Which Loop to Use? The three forms of loop statements, while, do-while, and for, are expressively equivalent; that is, you can write a loop in any of these three forms. For example, a while loop in (a) in the following figure can always be converted into the following for loop in (b): A for loop in (a) in the following figure can generally be converted into the following while loop in (b) except in certain special cases (see Review Question 3.19 for one of them):
54
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 54 Recommendations Use the one that is most intuitive and comfortable for you. o In general, a for loop may be used if the number of repetitions is known, as, for example, when you need to print a message 100 times. o A while loop may be used if the number of repetitions is not known, as in the case of reading the numbers until the input is 0 (use counter). o A do-while loop can be used to replace a while loop if the loop body has to be executed before testing the continuation condition.
55
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 55 Loop Comparison for loop: do loop: while loop: When to use If you know, prior to the start of loop, how many times you want to repeat the loop. If you always need to do the repeated thing at least one time. If you can't use a for loop or a do loop. Template for (int i=0; i<max; i++) { } do { } while ( ); while ( ) { }
56
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 56 Nested Loops F Nested loops = a loop within a loop. F Example – Write a program that prints a rectangle of characters where the user specifies the rectangle's height, the rectangle's width, and the character's value. Sample session: Enter height: 4 Enter width: 3 Enter character: < <<<
57
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 57 Nested Loops import java.util.Scanner; public class RecAngle1 { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); int height, width; // rectangle's dimensions char printCharacter; // this character forms the rectangle System.out.print("Enter height: "); height = stdIn.nextInt(); System.out.print("Enter width: "); width = stdIn.nextInt(); System.out.print("Enter character: "); printCharacter = stdIn.next().charAt(0); for (int row=1; row<=height; row++) { for (int col=1; col<=width; col++) { System.out.print(printCharacter); } //end of nested for System.out.println(); } //end of for } // end main } // end class Rectangle
58
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 58 Boolean Variables F Programs often need to keep track of the state of some condition. F For example, if you're writing a program that simulates the operations of a garage door opener, you'll need to keep track of the state of the garage door's direction and the direction up or down? F You need to keep track of the direction "state" because the direction determines what happens when the garage door opener's button is pressed. F If the direction state is up, then pressing the garage door button causes the direction to switch to down. F If the direction state is down, then pressing the garage door button causes the direction to switch to up. To implement the state of some condition, use a boolean variable.
59
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 59 Nested Loops Problem: Write a program that uses nested for loops to print a multiplication table. MultiplicationTable public class MultiTable { /** Main method */ public static void main(String[] args) { // Display the table heading System.out.println(" Multiplication Table"); // table title – display a title on the first line in the output // Display the number title System.out.print(" "); for (int j = 1; j <= 9; j++) //this for loop display the numbers 1 through 9 on the second line. System.out.print(" " + j); System.out.println("\n-----------------------------------------"); // the dash (-) line displayed on the third line // Print table body for (int i = 1; i <= 9; i++) { //outer loop with the control variable i in the outer loop System.out.print(i + " | "); for (int j = 1; j <= 9; j++) { // Display the product and align properly //inner loop with the control variable j in the inner loop System.out.printf("%4d", i * j); // for each I, the product I * j is displayed on a line in the inner loop. } //with j begin 1, 2, 3, …9. System.out.println(); } } }
60
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 60 Minimizing Numerical Errors Numeric errors involving floating-point numbers are expected. This section discusses how to minimize such errors through an example. Listing 4.7. Here is an example that sums a series that starts with 0.01 and ends with 1.0. The numbers in the series will increment by 0.01, as follows: 0.01 + 0.02 + 0.03 and so on. public class TestSum { public static void main(String[] args) { // Initialize sum float sum = 0; // Add 0.01, 0.02,..., 0.99, 1 to sum for (float i = 0.01f; i <= 1.0f; i = i + 0.01f) sum += i; // Display result System.out.println("The sum is " + sum); } } TestSum Video Link: Problem TestSum Problem TestSum
61
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 61 Problem: Finding the Greatest Common Divisor Problem: Write a program that prompts the user to enter two positive integers and finds their greatest common divisor. Solution: Suppose you enter two integers 4 and 2, their greatest common divisor is 2. Suppose you enter two integers 16 and 24, their greatest common divisor is 8. So, how do you find the greatest common divisor? Let the two input integers be n1 and n2. You know number 1 is a common divisor, but it may not be the greatest commons divisor. So you can check whether k (for k = 2, 3, 4, and so on) is a common divisor for n1 and n2, until k is greater than n1 or n2. GreatestCommonDivisorRun
62
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 62 import java.util.Scanner; public class GreatestCommonDivisor { /** Main method */ public static void main(String[] args) { // Create a Scanner Scanner input = new Scanner(System.in); // Prompt the user to enter two integers System.out.print("Enter first integer: "); int n1 = input.nextInt(); System.out.print("Enter second integer: "); int n2 = input.nextInt(); int gcd = 1; int k = 2; while (k <= n1 && k <= n2) { if (n1 % k == 0 && n2 % k == 0) gcd = k; k++; } System.out.println("The greatest common divisor for " + n1 + " and " + n2 + " is " + gcd); } }
63
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 63 Problem: Predicating the Future Tuition- Listing 4.9 double tuition = 10000; int year = 1 // Year 1 tuition = tuition * 1.07; year++; // Year 2 tuition = tuition * 1.07; year++; // Year 3 tuition = tuition * 1.07; year++; // Year 4... FutureTuitionRun
64
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 64 Problem: Predicating the Future Tuition Problem: Suppose that the tuition for a university is $10,000 this year and tuition increases 7% every year. In how many years will the tuition be doubled? Before you write this program try to solve this problem first by hand. FutureTuition Run public class FutureTuition { public static void main(String[] args) { double tuition = 10000; // Year 1 int year = 1; while (tuition < 20000) { tuition = tuition * 1.07; year++; } System.out.println("Tuition will be doubled in " + year + " years"); } }
65
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 65 Problem: Monte Carlo Simulation The Monte Carlo simulation refers to a technique that uses random numbers and probability to solve problems. This method has a wide range of applications in computational mathematics, physics, chemistry, and finance. This section gives an example of using the Monte Carlo simulation for estimating . Assume the radius of the Circle is 1, area is and the square area is 4. MonteCarloSimulation Run circleArea / squareArea = / 4. can be approximated as 4 * numberOfHits / 1000000.
66
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 66 public class MonteCarloSimulation { public static void main(String[] args) { final int NUMBER_OF_TRIALS = 10000000; int numberOfHits = 0; for (int i = 0; i < NUMBER_OF_TRIALS; i++) { double x = Math.random() * 2.0 - 1; double y = Math.random() * 2.0 - 1; if (x * x + y * y <= 1) numberOfHits++; } //end of while double pi = 4.0 * numberOfHits / NUMBER_OF_TRIALS; System.out.println("PI is " + pi); } // end of main method } //end of class Problem: Monte Carlo Simulation Web link: Class MathClass Math Web Link: About Monte Carlo Simulation - IntroductionAbout Monte Carlo Simulation - Introduction
67
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 67 Using break and continue Examples for using the break and continue keywords that can be used in loop statements to provide additional controls. F TestBreak.java // you have to used the keyword break in a switch statement // you can use break in a loop to immediately terminate the loop. F TestContinue.java TestBreak TestContinue
68
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 68 Guessing Number Problem Revisited Here is a program for guessing a number. You can rewrite it using a break statement. Listing 4.11 public class TestBreak { public static void main(String[] args) { int sum = 0; int number = 0; while (number = 100) break; // goes to println } System.out.println("The number is " + number); System.out.println("The sum is " + sum); } } GuessNumberUsing Break
69
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 69 Guessing Number Problem Revisited Here is a program for guessing a number. You can rewrite it using a continue statement. Listing 4.12 public class TestContinue { public static void main(String[] args) { int sum = 0; int number = 0; while (number < 20) { number++; if (number == 10 || number == 11) continue; sum += number; } //end of while System.out.println("The sum is " + sum); } //end of main method } //end of class Test Continue
70
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 70 Problem: Displaying Prime Numbers Problem: Write a program that displays the first 50 prime numbers in five lines, each of which contains 10 numbers. An integer greater than 1 is prime if its only positive divisor is 1 or itself. For example, 2, 3, 5, and 7 are prime numbers, but 4, 6, 8, and 9 are not. Solution: The problem can be broken into the following tasks: For number = 2, 3, 4, 5, 6,..., test whether the number is prime. Determine whether a given number is prime. Count the prime numbers. Print each prime number, and print 10 numbers per line. PrimeNumberRun
71
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Exercise 4_22 Financial application: Loan repayment schedule 71 Video Link: Exercise 4_22Exercise 4_22 Please refer to companion website for the program.
72
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 72 (GUI) Controlling a Loop with a Confirmation Dialog A sentinel-controlled loop can be implemented using a confirmation dialog. The answers Yes or No to continue or terminate the loop. The template of the loop may look as follows: int option = 0; while (option == JOptionPane.YES_OPTION) { System.out.println("continue loop"); option = JOptionPane.showConfirmDialog(null, "Continue?"); } SentinelValueUsingConfirmationDialogRun
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.