Download presentation
Presentation is loading. Please wait.
Published byVanessa Ford Modified over 9 years ago
1
Loops Copyright © 2012 Pearson Education, Inc.
2
Conditionals and Loops (Chapter 5) So far, we’ve looked at: –making decisions with if –how to compare data –Boolean expressions –Working with Collections of objects (i.e., ArrayList) –repeat processing steps using a for-each loop Today we’ll look at: –While loops –For loops Copyright © 2012 Pearson Education, Inc.
3
Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements, they are controlled by boolean expressions We’ll use three kinds of Java repetition statements in this class: while, for, and for -each loops Copyright © 2012 Pearson Education, Inc.
4
The while Statement A while statement has the following syntax: while ( condition ) statement; If the condition is true, the statement is executed Then the condition is evaluated again, and if it is still true, the statement is executed again The statement is executed repeatedly until the condition becomes false Copyright © 2012 Pearson Education, Inc.
5
Logic of a while Loop statement true false condition evaluated Copyright © 2012 Pearson Education, Inc.
6
The while Statement An example of a while statement: If the condition of a while loop is false initially, the statement is never executed Therefore, the body of a while loop will execute zero or more times int count = 1; while (count <= 5) { System.out.println (count); count++; } Copyright © 2012 Pearson Education, Inc. Sample Run 1 2 3 4 5
7
The General While Statement (with an index) initialization; while ( condition ) { statement; increment; } Copyright © 2012 Pearson Education, Inc.
8
The for Statement: a condensed while A for statement has the following syntax: for ( initialization ; condition ; increment ) statement; The initialization is executed once before the loop begins The statement is executed until the condition becomes false The increment portion is executed at the end of each iteration Copyright © 2012 Pearson Education, Inc.
9
Logic of a for loop statement true condition evaluated false increment initialization Copyright © 2012 Pearson Education, Inc.
10
The for Statement An example of a for loop: for (int count=1; count <= 5; count++) System.out.println (count); The initialization section can be used to declare a variable Like a while loop, the condition of a for loop is tested prior to executing the loop body Therefore, the body of a for loop will execute zero or more times Copyright © 2012 Pearson Education, Inc. Sample Run 1 2 3 4 5
11
The for Statement The increment section can perform any calculation: for (int num=100; num > 0; num -= 5) System.out.println (num); A for loop is well suited for executing statements a specific number of times that can be calculated or determined in advance (i.e., with an index) See Multiples.java (p. 281) See Stars.java (p. 283) Copyright © 2012 Pearson Education, Inc. Sample Run 100 95 90 85 80... 15 10 5
12
What does this do? // Print multiples of 3 that are below 40. for(int num = 3; num < 40; num = num + 3) { System.out.println(num); }
13
Do this: for(int num = -10; num <= 10; num += 2) { System.out.println(num); } // Print even number between -10 and 10 inclusive
14
Sentinel Values (while) Let's look at some examples of loop processing A loop can be used to maintain a running sum A sentinel value is a special input value that represents the end of input See Average.java Copyright © 2012 Pearson Education, Inc.
15
//******************************************************************** // Average.java Author: Lewis/Loftus // // Demonstrates the use of a while loop, a sentinel value, and a // running sum. //******************************************************************** import java.text.DecimalFormat; import java.util.Scanner; public class Average { //----------------------------------------------------------------- // Computes the average of a set of values entered by the user. // The running sum is printed as the numbers are entered. //----------------------------------------------------------------- public static void main (String[] args) { int sum = 0, value, count = 0; double average; Scanner scan = new Scanner (System.in); System.out.print ("Enter an integer (0 to quit): "); value = scan.nextInt(); continue
16
Copyright © 2012 Pearson Education, Inc. continue while (value != 0) // sentinel value of 0 to terminate loop { count++; sum += value; System.out.println ("The sum so far is " + sum); System.out.print ("Enter an integer (0 to quit): "); value = scan.nextInt(); } continue
17
Copyright © 2012 Pearson Education, Inc. continue System.out.println (); if (count == 0) System.out.println ("No values were entered."); else { average = (double)sum / count; DecimalFormat fmt = new DecimalFormat ("0.###"); System.out.println ("The average is " + fmt.format(average)); }
18
Copyright © 2012 Pearson Education, Inc. continue System.out.println (); if (count == 0) System.out.println ("No values were entered."); else { average = (double)sum / count; DecimalFormat fmt = new DecimalFormat ("0.###"); System.out.println ("The average is " + fmt.format(average)); } Sample Run Enter an integer (0 to quit): 25 The sum so far is 25 Enter an integer (0 to quit): 164 The sum so far is 189 Enter an integer (0 to quit): -14 The sum so far is 175 Enter an integer (0 to quit): 84 The sum so far is 259 Enter an integer (0 to quit): 12 The sum so far is 271 Enter an integer (0 to quit): -35 The sum so far is 236 Enter an integer (0 to quit): 0 The average is 39.333
19
Input Validation A loop can also be used for input validation, making a program more robust It's generally a good idea to verify that input is valid (in whatever sense) when possible See WinPercentage.java Copyright © 2012 Pearson Education, Inc.
20
//******************************************************************** // WinPercentage.java Author: Lewis/Loftus // // Demonstrates the use of a while loop for input validation. //******************************************************************** import java.text.NumberFormat; import java.util.Scanner; public class WinPercentage { //----------------------------------------------------------------- // Computes the percentage of games won by a team. //----------------------------------------------------------------- public static void main (String[] args) { final int NUM_GAMES = 12; int won; double ratio; Scanner scan = new Scanner (System.in); System.out.print ("Enter the number of games won (0 to " + NUM_GAMES + "): "); won = scan.nextInt(); continue
21
Copyright © 2012 Pearson Education, Inc. continue while (won NUM_GAMES) { System.out.print ("Invalid input. Please reenter: "); won = scan.nextInt(); } ratio = (double)won / NUM_GAMES; NumberFormat fmt = NumberFormat.getPercentInstance(); System.out.println (); System.out.println ("Winning percentage: " + fmt.format(ratio)); }
22
Copyright © 2012 Pearson Education, Inc. continue while (won NUM_GAMES) { System.out.print ("Invalid input. Please reenter: "); won = scan.nextInt(); } ratio = (double)won / NUM_GAMES; NumberFormat fmt = NumberFormat.getPercentInstance(); System.out.println (); System.out.println ("Winning percentage: " + fmt.format(ratio)); } Sample Run Enter the number of games won (0 to 12): -5 Invalid input. Please reenter: 13 Invalid input. Please reenter: 7 Winning percentage: 58%
23
Infinite Loops The body of a while loop eventually must make the condition false If not, it is called an infinite loop, which will execute until the user interrupts the program An example of an infinite loop: This loop will continue executing until interrupted (Control-C) or until an underflow error occurs int count = 1; while (count <= 25) { System.out.println (count); count = count - 1; } Copyright © 2012 Pearson Education, Inc. Sample Run 1 0 -2 -3 -4 -5 -6... Never ends!!!
24
Nested Loops Similar to nested if statements, loops can be nested as well That is, the body of a loop can contain another loop (or if statements, etc.) For each iteration of the outer loop, the inner loop iterates completely See PalindromeTester.java Copyright © 2012 Pearson Education, Inc.
25
//******************************************************************** // PalindromeTester.java Author: Lewis/Loftus // // Demonstrates the use of nested while loops. //******************************************************************** import java.util.Scanner; public class PalindromeTester { //----------------------------------------------------------------- // Tests strings to see if they are palindromes. //----------------------------------------------------------------- public static void main (String[] args) { String str, another = "y"; int left, right; Scanner scan = new Scanner (System.in); while (another.equalsIgnoreCase("y")) // allows y or Y { System.out.println ("Enter a potential palindrome:"); str = scan.nextLine(); left = 0; right = str.length() - 1; continue
26
Copyright © 2012 Pearson Education, Inc. continue while (str.charAt(left) == str.charAt(right) && left < right) { left++; right--; } System.out.println(); if (left < right) System.out.println ("That string is NOT a palindrome."); else System.out.println ("That string IS a palindrome."); System.out.println(); System.out.print ("Test another palindrome (y/n)? "); another = scan.nextLine(); }
27
Copyright © 2012 Pearson Education, Inc. continue while (str.charAt(left) == str.charAt(right) && left < right) { left++; right--; } System.out.println(); if (left < right) System.out.println ("That string is NOT a palindrome."); else System.out.println ("That string IS a palindrome."); System.out.println(); System.out.print ("Test another palindrome (y/n)? "); another = scan.nextLine(); } Sample Run Enter a potential palindrome: radar That string IS a palindrome. Test another palindrome (y/n)? y Enter a potential palindrome: able was I ere I saw elba That string IS a palindrome. Test another palindrome (y/n)? y Enter a potential palindrome: abracadabra That string is NOT a palindrome. Test another palindrome (y/n)? n
28
Quick Check Copyright © 2012 Pearson Education, Inc. How many times will the string "Here" be printed? count1 = 1; while (count1 <= 10) { count2 = 1; while (count2 < 20) { System.out.println ("Here"); count2++; } count1++; }
29
Quick Check Copyright © 2012 Pearson Education, Inc. How many times will the string "Here" be printed? count1 = 1; while (count1 <= 10) { count2 = 1; while (count2 < 20) { System.out.println ("Here"); count2++; } count1++; } 10 * 19 = 190
30
Review: Loop Templates Copyright © 2012 Pearson Education, Inc. While Loop Index Template: initialize index while (condition){ statements to be repeated update index } For Loop Template: for (initialize index; condition; update index){ statements to be repeated } For Each Loop Template: for (ElementType elementName : collection){ statements to be repeated } While Loop Sentinel Template: get input value while (input != end condition){ statements to be repeated get input value }
31
Practice! Test in main Write a for loop that prints out the numbers 1 to 26 on a single line, separated by spaces: 1 2 3 4 5 6 7 8 9 10 … 20 21 22 23 24 25 26 Write a for loop that prints out the letters A to Z on a single line, separated by spaces: A B C D E F G H I J … T U V W X Y Z Hint: maybe your loop variable should be a char rather than an int Copyright © 2012 Pearson Education, Inc.
32
Practice! continued Write a for loop that prints out all the multiples of 5, from 0 to 100 (inclusive). Write a while loop that prints out all the multiples of 3, from 0 to 21 (inclusive). Write a while loop that prints out random numbers from 1 to 10 (inclusive) until the number 0 is generated. Copyright © 2012 Pearson Education, Inc.
33
else-if & switch Copyright © 2012 Pearson Education, Inc.
34
Example: else-if Copyright © 2012 Pearson Education, Inc. int grade = 85; char letter = ‘’; if (grade > 89) letter = ‘A’; else if (grade > 79) letter = ‘B’; else if (grade > 69) letter = ‘C’; else if (grade > 59) letter = ‘D’; else letter = ‘F’; int grade = 85; char letter = ‘’; if (grade > 89) letter = ‘A’; else if (grade > 79) letter = ‘B’; else if (grade > 69) letter = ‘C’; else if (grade > 59) letter = ‘D’; else letter = ‘F’;
35
The switch Statement The switch statement provides another way to decide which statement to execute next The switch statement evaluates an expression, then attempts to match the result to one of several possible cases Each case contains a value and a list of statements The flow of control transfers to statement associated with the first case value that matches Copyright © 2012 Pearson Education, Inc.
36
The switch Statement The general syntax of a switch statement is: switch ( expression ) { case value1 : statement-list1 case value2 : statement-list2 case value3 : statement-list3 case... } switch and case are reserved words If expression matches value2, control jumps to here Copyright © 2012 Pearson Education, Inc. A break statement can be used in a switch to jump to the end of the switch statement
37
The switch Statement switch (option) { case 'A': aCount++; break; case 'B': bCount++; break; case 'C': cCount++; break; } An example of a switch statement: Copyright © 2012 Pearson Education, Inc.
38
Example: else-if vs switch Copyright © 2012 Pearson Education, Inc. int grade = 85; char letter = ‘’; if (grade > 89) letter = ‘A’; else if (grade > 79) letter = ‘B’; else if (grade > 69) letter = ‘C’; else if (grade > 59) letter = ‘D’; else letter = ‘F’; int grade = 85; char letter = ‘’; if (grade > 89) letter = ‘A’; else if (grade > 79) letter = ‘B’; else if (grade > 69) letter = ‘C’; else if (grade > 59) letter = ‘D’; else letter = ‘F’; int grade = 85; char letter = ‘’; switch (grade) { case 100: case 99: case 98: … case 90: letter = ‘A’; break; case 89: … default: letter = ‘F’; } int grade = 85; char letter = ‘’; switch (grade) { case 100: case 99: case 98: … case 90: letter = ‘A’; break; case 89: … default: letter = ‘F’; } If no other case value matches, the optional default case will be executed (if present)
39
The switch Statement The type of a switch expression must be integers, characters, or enumerated types Why? 109.54 == 109.542 Copyright © 2012 Pearson Education, Inc. As of Java 7, a switch can also be used with strings You cannot use a switch with floating point values The implicit boolean condition in a switch statement is equality You cannot perform relational checks with a switch statement (i.e., > or <)
40
Copyright © 2012 Pearson Education, Inc. //******************************************************************** // GradeReport.java Author: Lewis/Loftus // // Demonstrates the use of a switch statement. //******************************************************************** import java.util.Scanner; public class GradeReport { //----------------------------------------------------------------- // Reads a grade from the user and prints comments accordingly. //----------------------------------------------------------------- public static void main (String[] args) { int grade, category; Scanner scan = new Scanner (System.in); System.out.print ("Enter a numeric grade (0 to 100): "); grade = scan.nextInt(); category = grade / 10; System.out.print ("That grade is "); continue
41
Copyright © 2012 Pearson Education, Inc. continue switch (category) { case 10: System.out.println ("a perfect score. Well done."); break; case 9: System.out.println ("well above average. Excellent."); break; case 8: System.out.println ("above average. Nice job."); break; case 7: System.out.println ("average."); break; case 6: System.out.println ("below average. You should see the"); System.out.println ("instructor to clarify the material " + "presented in class."); break; default: System.out.println ("not passing."); } Sample Run Enter a numeric grade (0 to 100): 91 That grade is well above average. Excellent.
42
Templates While Loop Index Template: initialize index while (condition){ statements to be repeated update index } For Loop Template: for(initialize index; condition; update index){ statements to be repeated } For Each Loop Template: for (ElementType elementName : collection){ statements to be repeated } While Loop Sentinel Template: get input value while (input != end condition){ statements to be repeated get input value } Example switch: switch (option) { case 'A': aCount++; break; case 'B': bCount++; break; case 'C': cCount++; break; }
43
The Conditional Operator The conditional operator evaluates to one of two expressions based on a boolean condition Its syntax is: condition ? expression1 : expression2 If the condition is true, expression1 is evaluated; if it is false, expression2 is evaluated The value of the entire conditional operator is the value of the selected expression Example: char pf = grade > 59 ? ‘P’ : ‘F’; Copyright © 2012 Pearson Education, Inc.
44
The Conditional Operator The conditional operator is similar to an if-else statement, except that it is an expression that returns a value For example: larger = ((num1 > num2) ? num1 : num2); If num1 is greater than num2, then num1 is assigned to larger ; otherwise, num2 is assigned to larger The conditional operator is ternary because it requires three operands Copyright © 2012 Pearson Education, Inc.
45
The Conditional Operator Another example: If count equals 1, the "Dime" is printed If count is anything other than 1, then "Dimes" is printed System.out.println ("Your change is " + count + ((count == 1) ? "Dime" : "Dimes")); Copyright © 2012 Pearson Education, Inc.
46
Quick Check Copyright © 2012 Pearson Education, Inc. Express the following logic in a succinct manner using the conditional operator. if (val <= 10) System.out.println("It is not greater than 10."); else System.out.println("It is greater than 10."); System.out.println("It is" + ((val <= 10) ? " not" : "") + " greater than 10.");
47
The do Statement A do statement has the following syntax: do { statement-list; } while (condition); The statement-list is executed once initially, and then the condition is evaluated The statement is executed repeatedly until the condition becomes false Copyright © 2012 Pearson Education, Inc.
48
Logic of a do Loop true condition evaluated statement false Copyright © 2012 Pearson Education, Inc.
49
The do Statement An example of a do loop: The body of a do loop executes at least once See ReverseNumber.java int count = 0; do { count++; System.out.println (count); } while (count < 5); Copyright © 2012 Pearson Education, Inc.
50
//******************************************************************** // ReverseNumber.java Author: Lewis/Loftus // // Demonstrates the use of a do loop. //******************************************************************** import java.util.Scanner; public class ReverseNumber { //----------------------------------------------------------------- // Reverses the digits of an integer mathematically. //----------------------------------------------------------------- public static void main (String[] args) { int number, lastDigit, reverse = 0; Scanner scan = new Scanner (System.in); continue
51
Copyright © 2012 Pearson Education, Inc. continue System.out.print ("Enter a positive integer: "); number = scan.nextInt(); do { lastDigit = number % 10; reverse = (reverse * 10) + lastDigit; number = number / 10; } while (number > 0); System.out.println ("That number reversed is " + reverse); } Sample Run Enter a positive integer: 2896 That number reversed is 6982
52
Comparing while and do statement true false condition evaluated The while Loop true condition evaluated statement false The do Loop Copyright © 2012 Pearson Education, Inc.
53
Create a CeilingFan Class Step 1: Create the class & field –Add a Speed enum {off, low, medium, high} –Store the fan’s current speed & initialize Step 2: Create the following method –changeSpeed that changes the speed w/ no parameters using a switch statement & prints the current speed –changeSpeed with 1 parameter (the number of times to change it) that uses the first changeSpeed() method & a loop
54
Homework CodingBat exercises Work on Project Copyright © 2012 Pearson Education, Inc.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.