🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

chapter 4_compressed_compressed_compressed-compressed.pdf

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Full Transcript

r o d u c e. d o n o t re p l u s e only, 9-22 du r s Chapter e o n a 4 0 2 4 -0 c c c d.e P 2 d ent.d...

r o d u c e. d o n o t re p l u s e only, 9-22 du r s Chapter e o n a 4 0 2 4 -0 c c c d.e P 2 d ent.d @ s tu Loops 3 8 and 1 1 9 71Files e p r o d u ce. , d o n o t re ly Topics l u s e onOperators9 -22 cd.edu a  4.1 The Increment and Decrement r s o n 0 2 4 - 0 cc Pe 2 d e n t.d 4.2 The while Loop  9 7 1 @ stu 1 381Loop for Input Validation ewhile e. 4.3 Using the  r o d u c d o n o t re p only, 9-22 4.4 The do-while Loop  n a l u s e - 0.e du P e r s o 2 0 2 4 c cc d ent.d 4.5 The for Loop  s tu d 3 8 1 4.6 Running Totals and Sentinel1 9 71@ Values e p r o d u ce. o t re 4.7 Nested Loops  , d o n 4.8 The break ande u s only Statements - 2 2 24-0 nt.dcccd.edu continue  on a l 9 (Optional) Pe4.9rsDeciding 2 0 Which Loop to Use de 9 7 1 @ stu  4.10 1 381 to File Input and Output eIntroduction  4.11 Generating Random Numbers with the Random Class  4.12 Common Errors to Avoid  4.1: The Increment andt rDecrement p r o d u ce. , d o n o e Operators l u s e o n l y 9 -2 2 du a Person 2024-0dent.dcccd.e CONCEPT: ++ and −−7 9 1 @ stu that add and subtract one from their operands. e3811 are operators To increment  a value means to increase it by one, and to decrement  a value means to decrease it by one. Both of the following statements increment the variable number: r oduc e. t r e p o no number = number + 1; n l y, d se o 4 - 0 9 - 2 2 number += 1; a l u du Pers o n 202 dent.dcccd.e 9 7 1 @ stu 1 e381 in both of the following statements: And number is decremented number = number − 1; number −= 1; e p r o d uce. , d o n ot r s e y nl just-for22incrementing and u odesigned s o n a u Java provides a set of simple unaryl operators 2 4 -09 dcccd.ed P e r 2 0. ntdecrement decrementing variables. The increment operator is ++ andethe @ s tu d operator is −−. 71 to increment number: e38 19 The following statement uses the1 ++ operator number++; e p r o d uce. l y, d And the following statement decrementso not: r number n a l u s e o n -0 9 -2 2.e du P e r s o 2 0 2 4 c cc d s tu d ent.d 8 1 1 9 7 1@ e3 number−−; NOTE: The expression number++ is pronounced “number plus plus,” and number−− is pronounced “number minus minus.” e p r o d uce. l y, d o not r l u s e on -2++2and −−coperators. 9the du e r s o n a The program in Code Listing  4-1 2 4 - 0 demonstrates 0 c d.e P 2 s tu d ent.dc 8 1 1 9 7 1@ e3 Code Listing 4-1 (IncrementDecrement.java) 1 o d uce. 4 e p r 5 public class IncrementDecrement l y, d o not r 6 { l u s on emain(String[]9 - 2 2args) du 7 {Per s o n a public static void 0 2 4 - 0 cc c d.e 8 2 d ent.dout with 4 s tu 9 3 8 1 1 9 71@ int number = 4; // number starts 10 11 e Display the value in number. // 12 System.out.println("number is " + number); 13 System.out.println("I will increment number."); 14 15 // Increment number. 16 number++; 17 18 d u c e. // Display the value in number again. r o 19 o t re p System.out.println("Now, number is " + number); d o n 20 u s e only, 9-22 System.out.println("I will decrement number."); e r s o n 21 a l 2 0 2 4 - 0 number.cccd.edu P 22 // Decrement d ent.d stu 71@ 23 number--; e 3 8 24 1 1 9 25 // Display the value in number once more. 26 System.out.println("Now, number is " + number); 27 } 28 } Program Output p r o d u ce. , d o n o t re l u s e o n l y 9 -2 2 u P ersoisn4a number 2 024-0 ent.dcccd.ed I will increment number.stud 1 5 71@ 9 3 8 1 Now, number is e I will decrement number. Now, number is 4 p r o d u ce.  o n ot re operators used The statements in Code Listing 4-1 show the increment and decrement , d s e ois n ly after the2variable. The operators  l u in postfix mode , which means the operator na the operator -2 4-09before placed.eduas also work in prefixPers,owhere mode 20is2placed ent.d thec c c d variable name s tu d follows: 3 8 1 1 9 71@ e ++number; −−number; p r o d u ce. , d o n o t re l u s e onlythese 9 -22 add conedto.eordsubtract u one from their o n a In both postfix and r s prefix mode, 2 4 - 0 operators Pe Code Listing 4-220demonstrates operand.  tu d e n t.dcc this. 1 1 9 7 1 @s e38 Code Listing 4-2 (Prefix.java) 1 n l y, d o no 5 a l u e o -0 9 -2 2 sPrefix du Pe{rs o n 2024 dent.dcccd.e 6 public class 7 1 u voidstmain(String[] @ 8 1 9 7 public static 8 1 args) 9 10 e3 { int number = 4; // number starts out with 4 11 12 // Display the value in number. 13 System.out.println("number is " + number); 14 System.out.println("I will increment number."); 15 16 // Increment number. 17 ++number; e p r o d uce. 18 , d o ot r nagain. 19 e // Display the value l iny on numbernumber 20 e r s o n a l u s 0 2 System.out.println("Now, 4 - 0 9-22is "c+cnumber); d.e du 21 P 2 System.out.println("I s will tu d ent.dc decrement number."); 22 8 1 1 9 7 1@ 23 e3 // Decrement number. 24 --number; 25 26 // Display the value in number once again. 27 System.out.println("Now, number is " + number); 28 } 29 } r oduc e. t r e p n l y, d o no u se o 4 - 0 9 - 2 2 Programl Output a du Pers o n 202 dent.dcccd.e 9 7 1 @ stu e3number 1 81 is 4 I will increment number. Now, number is 5 I will decrement number. Now, number is 4 e p r o d uce. l y, d o not r l u s e on 9-22and duModes e r s o n a 0 2 4 - 0 cc d.e P 2 ent.dc The Difference between Postfix Prefix s tu d 8 1 1 9 7 1@ e3  In Code Listings 4-1 and 4-2 , the statements number++ and ++number increment the variable number, while the statements number-- and --number decrement the variable number. In these simple statements, it doesn’t matter whether the operator is used in postfix or prefix mode. The difference is important, however, when these operators are used in statements that do more than just increment or decrement. For example, look at the following code: o duce. r e p r l y, d o not n a l u s e o n -0 9 -2 2.e du P e r s o 2 0 2 4 cc c d number = 4; s tu d ent.d 3 8 1 1 9 System.out.println(number++); 71@ e The statement that calls the println method does two things: (1) calls println to display the value of number, and (2) increments number. But which happens first? The println method will display a different value if number is incremented first than if p r o d u ce. number is incremented last. The answer depends upon the mode of the increment , d o n o t re o n l y 9 -2 2 operator. a l u se du Person 2024-0dent.dcccd.e 9 7 1 @ stu 3811 7 e38119 Postfix mode causes the increment to happen after the value of the variable is used in the expression. In the previously shown statement, the println method will display 4 and then number will be incremented to 5. Prefix mode, however, causes the increment to happen first. Here is an example: o duce. r e p r l y, d o not number = 4; n a l u s e o n -0 9 -2 2.e du P e r s o System.out.println(++number); 2 0 2 4 cc c d s tu d ent.d 3 8 1 1 9 71@ e In these statements, number is incremented to 5, then println will display the value in number (which is 5). For another example, look at the following code: int x = 1, y; p r o d u ce. y = x++; // Postfix increment , d o n o t re l u s e o n l y 9 -2 2 du e r s o n a 0 2 4 - 0 c cc d.e P 2 d ent.d s tu @ with the value 1) and the variable 3 8 1 1 9 The first statement declares the variable7x 1 (initialized e y. The second statement does the following: It assigns the value of x to the variable y. The variable x is incremented. p r o d u ce. The value that will be stored in y depends on when the increment takes place. Because d o n t rethe assignment takes place. So, this oafter y, othenlcode the ++ operator is used in postfix mode, e it acts s o n a l u s 4 - 0 9 22 x willdcontain -executed,.edu2. Let’s look at the same P e r code will store 1 in y. After 2 0 2 has d c c c. as follows: s code, but with the ++ operator usedtu entmode dprefix 1 1 9 71 @ in e 3 8 int x = 1, y; y = ++x; // Prefix increment e p r o d uce. The first statement declares the variable x (initializedn , d o otther value 1) and the variable y with u y. In the second statement,l thes e onl is used 2 mode, so it acts on the 9-in2prefix e r s o n a ++ operator 0 2 4 - 0 P 2 cd.edu td c c e n t.d c ccd 9 7 1 stud variable before the assignment takes place. So, this code will store 2 in y. After the code @ e3 also11 has executed, x will 8 contain 2. r oduc e. t r e p n l y, d o no a l u se o 4-09-22 du Pers o n 202 dent.dcccd.e 9 7 1 @ stu e381 1 r oduc e. t r e p n l y, d o no a l u se o 4 - 0 9 - 2 2 du Pers o n 202 dent.dcccd.e 9 7 1 @ stu e381 1 e p r o d uce. l y, d o not r l u s e on 9-22 ccd.edu e r s o n a 0 2 4 - 0 P 2 s tu d ent.dc 8 1 1 9 7 1@ e3 o duce. ot r e p r o n l y, do n r s o n a l use Pe 9 22 d Perso - 0 9 -22 cd.edu 20 2 4 t.dcc stu d e n e38 11971@ 4.2: The while Loop p r o d u ce. , d o n o t re e y oofna lprogram CONCEPT: Aa s o n l uisspart 4 - 0 9 22repeats. d.edu -that Pe r loop 20 2 n t.d c cc stud e 9 7 1 @ e3811 VideoNote 4-1 The while Loop p r o d u ce. , d o n o t re l u se o n l y 9 -2 2 du a Person 2024-0dent.dcccd.e 9 7 1 @ stu e3811 In Chapter 3  , you were introduced to the concept of control structures, which direct the flow of a program. A loop  is a control structure that causes a statement or group of statements to repeat. Java has three looping control structures: the while loop, the do- while loop, and the for loop. The difference among each of these is how they control the repetition. In this section we will focus on the while loop. p r o d u ce. , d o n o t re u s (1)o e nly -22 that is tested u n a l The while loop has two important parts: r s o - 0 9 a boolean expression 2 4 c d.e d for a 0 of statements Peand (2) a statement or2block d e n ccis repeated as long t.dthat true or false value, 1 @ s tu 1 1 9 7 e38 as the expression is true. Figure 4-1 shows the logic of a while loop. Figure 4-1 Logic of a while loop o duce. r e p r l y, d o not n a l u s e o n -0 9 -2 2.e du Pe r s o 2 0 2 4 c cc d s tu d ent.d 3 8 1 1 9 71@ e e e p r o d uce. , d o n ot r se y o n l 9 -2 2 a l u du Person 2024-0dent.dcccd.e 9 7 1 @ stu e381 1 Figure 4-1 Full Alternative Text  e p r o d uce. Here is the general format of the while loop: , d o n ot r s e y o n l 9 -2 2 a l u du Person 2024-0dent.dcccd.e 9 7 1 @ stu e381 while (BooleanExpression) 1 Statement; In the general format, BooleanExpression is any valid boolean expression, and Statement is any valid Java statement. The first line shown in the format is sometimes p r o d u ce. called the loop header . It consists of the keyword while followed by the , d o n o t re y o n l 9 -2 2 BooleanExpression enclosed in parentheses. s e so n a l u 2 4-0 t.dcccd.edu P e r 2 0 @ s tu den Here’s how the loop works: The BooleanExpression is tested, and if it is true, the Statement is 11971 e38executed. Then, the BooleanExpression is tested again. If it is true, the Statement is executed. This cycle repeats until the BooleanExpression is false. The statement that is repeated is known as the body of the loop . It is also considered a conditionally executed statement, because it is only executed under the condition that the BooleanExpression is true. p r o d u ce. l y, do n o t re e o n onal us 9 22 d r s o n a l use 9 -22 cd.edu Pe 20 2 4 - 0 Notice there is no semicolon at the end of the loop header. Like the if statement, the dcc statement that follows it. tu d e n t.executed @s while loop is not complete without the conditionally 1 1 9 7 1 e38 If you wish the while loop to repeat a block of statements, the format is as follows: while (BooleanExpression) { o duce. Statement; r e p r Statement; l y, d o not n a l u s e o n -0 9 -2 2 // Place as many statements here.e du e r s // as necessary. P o 2 0 2 4 c cc d } s tu d ent.d 3 8 1 1 9 71@ e The while loop works like an if statement that executes over and over. As long as the expression in the parentheses is true, the conditionally executed statement or block will repeat. The program in Code Listing 4-3  uses the while loop to print “Hello” five times. r o d u ce. d o Code Listing 4-3 (WhileLoop.java) n o t re p l u s e only, 9-22 du e r s o n a 0 2 4 - 0 c c c d.e P 2 d ent.d s tu 1@ demonstrates the while loop. 1 2 This 4 5 public class WhileLoop 6 { 7 public static void main(String[] args) 8 { 9 int number = 1; 10 o duce. 11 while (number count++;...> } When you press the Enter key after the last } character, you should see the # p r o d u ce. o t re character displayed 10 times. Figure 4-4  shows an example of how your , d o n l u s o n l y 9 -2 2 completed JShell session should appear. e du e r s o n a 0 2 4 - 0 c c c d.e P 2 d nt.d esession s tu Figure 4-4 Completed 3 8 1 1 9 71@ JShell e o duce. r e p r l y, d o not n a l u s e o n -0 9 -2 2.e du Pe r s o 2 0 2 4 c cc d s tu d ent.d 3 8 1 1 9 71@ e Figure 4-4 Full Alternative Text  r o d u c e. o n o re p tProgram In the Spotlight: n o ly, d Designing a with a while n s e al u 024-09-2 cccd.edu 2 e r s Loop o 2 at Chemical P A project currently underway d Inc., requires that a substance be s tu d ent.Labs, 3 8 1 1 9 7in1a @ e continually heated vat. A technician must check the substance’s temperature every 15 minutes. If the substance’s temperature does not exceed 102.5 degrees Celsius, then the technician does nothing. However, if the temperature is greater than 102.5 degrees Celsius, the technician must turn down the vat’s thermostat, wait 5 minutes, and check the temperature again. The technician repeats these steps until the temperature does not exceed 102.5 degrees Celsius. The director of engineering has asked you to write a program that guides the technician p r odu ce. through this process. no t r e d o n o t re p Here is the algorithm: u s e o nly, d -22 rson P1.ePrompt al 2 0 2 4-09 t.dcccd.edu @ stu den the user to enter the substance’s temperature. 71 e38119 steps as long as the temperature is greater than 102.5 2. Repeat the following degrees Celsius: a. Tell the technician to turn down the thermostat, wait 5 minutes, and check the temperature again. b. Prompt the user to enter the substance’s temperature. p r o d u ce. 3. After the loop finishes, tell the technician that the temperature is acceptable and to check it again in 15 minutes. , d o n o t re s e y o n l 9 -2 2 a l u son you realize -0 2(a) andd2(b) 24Steps c d dube.enot eralgorithm, Pthis 20that nt. c c dethan After reviewing should 1 @ s tu 8 1 1 9 7 performed if the test condition (temperature is greater 102.5) is false to 3 will work well in this situation, because it will not begin with. The while eloop execute even once if its condition is false. Code Listing 4-4  shows the program. Code Listing 4-4 (CheckTemperature.java) p r o d u ce. , d o n o t re l u s e o n l y 9 -2 2 u a 024-0 ent.dcccd.ed Person1 import2java.util.Scanner 7 1 @ s tud 9 e38311 7 public class CheckTemperature 8 { 9 public static void main(String[] args) 10 { p r o d u ce. o t re 11 final double MAX_TEMP = 102.5; // , d o n o n l y 9 -2 2 Maximum temperature 12 a l u se double temperature; du // To Person 2024-0dent.dcccd.e hold the temperature 13 9 7 1 @ stu e381 14 1 input. // Create a Scanner object for keyboard 15 Scanner keyboard = new Scanner(System.in) 16 17 // Get the current temperature. 18 System.out.print("Enter the substance’s Celsius temperature: "); 19 temperature = keyboard.nextDouble(); 20 21 // As long as necessary, instruct the o d uce. e p r technician l y, d o not r e o n -0 9 -2 2 22 // to adjust the temperature. 23 a l u s while (temperature > MAX_TEMP) o n 4.e du Pe r s 2 0 2 cc c d ent.d 24 { s tu d 71@ 25 System.out.println("The temperature is e 3 8 1 1 9 too high. Turn the"); 26 System.out.println("thermostat down and wait 5 minutes."); 27 System.out.println("Then, take the Celsius temperature again"); 28 System.out.print("and enter it here: "); 29 temperature = keyboard.nextDouble(); 30 } 31 o duce. r e p r 32 l y, d not // Remind the technician to check the o e o n -0 9 -2 2 temperature o n a 33 l u s // again in 15 minutes. 4.e du Pe r s 2 0 2 c c c d ent.d 34 System.out.println("The temperature is s tu d 71@ acceptable."); e 3 8 1 35 1 9 System.out.println("Check it again in 15 minutes."); 36 } 37 } Program Output with Example Input Shown in Bold uce. e p r od t r o n l y, do no s o n a l use 24Celsius - 0 9 - 2 2temperature: c d.e du e r P [Enter] 2 0 c c ent.d Enter the substance’s 104.7 s tu d 3 8 1 1 9 The temperature 71is@too high. Turn the e thermostat down and wait 5 minutes. Then, take the Celsius temperature again and enter it here: 103.2 [Enter] The temperature is too high. Turn the thermostat down and wait 5 minutes. Then, take the Celsius temperature again and enter it here: 102.1 [Enter] The temperature is acceptable. Check it again in 15 minutes. o d uce. e p r l y, d o not r n a l u s e o n -0 9 -2 2.e du Pe r so 2 0 2 4 c cc d s tu d ent.d 3 8 1 1 9 71@ e p r o d u ce. , d o n o t re l u s e o n l y 9 -2 2 du a Person 2024-0dent.dcccd.e 9 7 1 @ stu e381 1 p r o d u ce. , d o n o t re l u se o n l y 9 -2 2 du a Person 2024-0dent.dcccd.e 9 7 1 @ stu e3811 p r o d u ce. , d o n o t re l u s e o n l y 9 -2 2 du a Person 2024-0dent.dcccd.e 9 7 1 @ stu e3811 r o duc e. r e p n l y, d o not a l u se o 4-09-22 du Pers o n 202 dent.dcccd.e 9 7 1 @ stu 381 1 7 1@ e38119 o duce. r e p r l y, d o not n a l u se o n -0 9 -2 2.e du Pe r s o 2 0 2 4 c c c d s tu d ent.d 3 8 1 1 9 71@ e e p r o d uce. l y, d o not r l u s e on 9-22 ccd.edu e r s o n a 0 2 4 - 0 P 2 s tu d ent.dc 8 1 1 9 7 1@ e3 4.3: Using the whilenLoop p r o d u ce. , d o o t re for Input l u s e o n l y 9 -2 2 du Validation e r s o n a 0 2 4 - 0 c c c d.e P 2 d ent.d s tu 1@can be used to create input routines that repeat until 3 8 1 1 CONCEPT: The while 9 7loop e acceptable data is entered. Perhaps the most famous saying of the computer industry is “garbage in, garbage out.” The integrity of a program’s output is only as good as its input, so you should try to make uce. sure garbage does not go into your programs. Input validation  is the process of e p r o d , d o n ot r inspecting data given to a program by the user and determining whether it is valid. A e y onl about u s 22 good program should give clear instructions the kind of input that is acceptable, r s o n a l 2 4 - 0 9 - c d.edu P e 2 0. d c c dent and not assume the user has followed those instructions. @ s tu The while loop e 38119useful is especially 71for validating input. If an invalid value is entered, a loop can require that the user reenter it as many times as necessary. For example, the loop in the following code asks for a number in the range of 1 through 100: p r o d u ce. int number; , d o n o t re u se n l y -2 2 forokeyboard9input. a l du 2024-0dent.dcccd.e Perso=nnew Scanner(System.in); // Create a Scanner object Scanner keyboard // Get a number from 1 1 9 7 1 @stu e38 a number in the range of 1 through 100: the user. System.out.print("Enter "); number = keyboard.nextInt(); // Validate the input. while (number < 1 || number > 100) { o duce. r e p r System.out.print("Invalid input. Enter a number in the range " + l y, d o not n a l u s e o n -0 9 -2 2 "of 1 through 100: ");.e du Pe r s o 2 0 4 number = keyboard.nextInt(); 2 cc c d } s tu d ent.d 3 8 1 1 9 71@ e This code first allows the user to enter a number. This takes place just before the loop. If the input is valid, the loop will not execute. If the input is invalid, however, the loop will display an error message and require the user to enter another number. The loop will ce. continue to execute until the user enters a valid number. The general logic of performing p r o d u o t re input validation is shown in Figure 4-5 . , d o n u se o n l y 9 -2 2 Figure 4-5 e P Input l na logic2024-0 rsovalidation c c cd.edu s tu d ent.d 3 8 1 1 9 71@ e o d uce. e p r l y, d o not r n a l u se o n -0 9 -2 2.e du Pe r s o 2 0 2 4 c c cd s tu d ent.d 3 8 1 1 9 71@ e p r o d u ce. , d o n o t re u s e o n l y 9 -2 2 P e rson Figure 4-5 Fulla l Alternative 2 0 24-0 nt.dcccd.edu Text @ s The read operation that takes place debefore the loop is called a priming read. It tujust 7 1 9 for the loop to test. Subsequent values are obtained by the loop. e3 first11 provides the8 value The program in Code Listing 4-5  calculates the number of soccer teams a youth league may create, based on a given number of players and a maximum number of players per team. The program uses while loops (in lines 29 through 35 and lines 42 through 46) to validate the user’s input. o duce. r e p r l y, d o not n a l u s e o n -0 9 -2 2.e du P e r s o 2 0 2 4 cc c d Code Listing 4-5 s tu d ent.d (SoccerTeams.java) 3 8 1 1 9 71@ e 1 import java.util.Scanner; 2 3 Perso 8 9 7 1 @ stu e3811 9 public class SoccerTeams 10 { 11 public static void main(String[] args) 12 { 13 final int MIN_PLAYERS = 9; // Minimum players per team 14 final int MAX_PLAYERS = 15; // Maximum players per team o duce. 15 r e p r 16 int players; l y, d o not // Number of n a l u s e o n -0 9 -2 2 available players.e du Pe r s o 17 2 0 2 4 int teamSize; cc c d // Number of players per team s tu d ent.d 18 3 8 1 1 9 71@ int teams; // Number of teams e 19 int leftOver; leftover players // Number of 20 21 // Create a Scanner object for keyboard input. 22 Scanner keyboard = new Scanner(System.in): 23 24 // Get the number of players per team. 25 e. System.out.print("Enter the number of players per r oduc team: "); t r e p 26 n l y, d o no teamSize = keyboard.nextInt(); 27 a l u se o 4-09-22 du Pers o n 202 dent.dcccd.e 28 // Validate the number entered. stu 29 while (teamSize < MIN_PLAYERS || teamSize > MAX_PLAYERS) 1 9 7 1 @ 30 31 e381 { System.out.print("The number must be at least " + MIN_PLAYERS + 32 " and no more than " + MAX_PLAYERS + 33 ".\nEnter the number of players: "); 34 teamSize = keyboard.nextInt(); p r o d u ce. o t re 35 } 36 , d o n 37 u se o n l y 9 -2 2 // Get the number of available players. l du a 38 Person 2024-0dent.dcccd.e System.out.print("Enter the available number of stu players: "); 9 7 1 @ e3811 39 players = keyboard.nextInt(); 40 41 // Validate the number entered. 42 while (players < 0) 43 { 44 System.out.print("Enter 0 or greater: "); 45 players = keyboard.nextInt(); 46 } 47 p r o d u ce. 48 , d o n o t re // Calculate the number of teams. o n l y 9 -2 2 49 teams = players / teamSize; 50 a l u s e du Person 51 2024-0dent.dcccd.e // Calculate the number of leftover players. 52 9 7 1 @ stu leftOver = players % teamSize; e381 53 54 1 // Display the results. 55 System.out.println("There will be " + teams + " teams with " + 56 leftOver + " players left over."); 57 } 58 } r o d u c e. d o n o t re p l u s e only, 9-22 u Bold din o n ProgramsOutput e r a with0Example 2 4 - 0 InputccShown c d.e P 2 d ent.d s tu 3 8 1 1 9 71@ e Enter the number of players per team: 4 [Enter] The number must be at least 9 and no more than 15. Enter the number of players: 12 [Enter] Enter the available number of players: -142 [Enter] Enter 0 or greater: 142 [Enter] There will be 11 teams with 10 players left over. e p r o d uce. , d o n ot r se y o n l 9 -2 2 a l u du Person 2024-0dent.dcccd.e 9 7 1 @ stu e381 1 p r o d u ce. , d o n o t re l u s e o n l y 9 -2 2 du a Person 2024-0dent.dcccd.e 9 7 1 @ stu e3811 p r o d u ce. , d o n o t re l u s e o n l y 9 -2 2 du a Person 2024-0dent.dcccd.e 9 7 1 @ stu e381 1 p r o d u ce. , d o n o t re l u se o n l y 9 -2 2 du a Person 2024-0dent.dcccd.e 9 7 1 @ stu e3811 4.4: The do-while Loop e p r o d uce. l y , d o not r l u s e on 9 - 22loop, which du its boolean e r s o n a 0 2 4 - 0 c c c d.e P CONCEPT: The do-while 2 loop is a ent.d posttest d means expression is tested after eachs 1@ tu 8 1 1 9 7 iteration. e3 The do-while loop looks something like an inverted while loop. Here is the do-while loop’s format when the body of the loop contains only a single statement: e p r o d uce. not r do Statement; l y, d o l u s e on 9 - 22 du e r s o n a while (BooleanExpression); 0 2 4 - 0 c c c d.e P 2 d ent.d 1@ s tu 8 1 1 9 7 e3 Here is the format of the do-while loop when the body of the loop contains multiple statements: do o d uce. e p r { l y, d o not r e o n -0 9 -2 2 Statement; Statement; o n a l u s 4.e du P e r s 2 0 2 cc c d ent.d // Place as many statements here as necessary. s tu d 1@ } while (BooleanExpression); 8 1 1 9 7 e3 NOTE: The do-while loop must be terminated with a semicolon. r o d u c e.  d o The do-while loop is a posttest loop. This n o t reitpdoes not test its boolean means l u s e onlyan, iteration. 9 - 22As a result,d.theeddo-while u s o n a expression until it has completed 4 - 0 loop always 202even ifdthe Per at least one iteration, e n t. boolean c dccexpression is false to begin with. u performs s t 71@of a while loop, which you will recall is a pretest loop. For This differs from the9behavior e 3 8 1 1 example, in the following while loop the println statement will not execute at all: uce. int x = 1; while (x < 0) e p r o d System.out.println(x); , d o n ot r s e y o n l 9 -2 2 a l u du Person 2024-0dent.dcccd.e 9 7 1 @ studo-while loop will execute once because the e381 1 But the println statement in the following do-while loop does not evaluate the expression x < 0 until the end of the iteration: int x = 1; uce. do e p r o d ot r System.out.println(x); while (x < 0); y, d o n l u se o n l 9 -2 2 du a Person 2024-0dent.dcccd.e 9 7 1 stu @loop. Figure 4-6  e38 1 illustrates the logic of1the do-while Figure 4-6 Logic of the do-while loop e p r o d uce. , d o n ot r s e y o n l 9 -2 2 a l u du Person 2024-0dent.dcccd.e 9 7 1 @ stu e381 1 e p r o d uce. l y, d o not r l u s e on 9-22 ccd.edu e r s o n a 0 2 4 - 0 P 2 s tu d ent.dc 8 1 1 9 7 1@ e3 Figure 4-6 Full Alternative  Text You should use the do-while loop when you want to make sure the loop executes at least once. For example, the program in Code Listing 4-6  averages a series of three test scores for a student. After the average is displayed, it asks the user whether he or she wants to average another set of test scores. The program repeats as long as the user enters Y for yes. p r o d u ce. , d o n o t re l u se o n l y 9 -2 2 du a Per4-6 Code Listing 2024-0dent.dcccd.e son(TestAverage1.java) 9 7 1 @ stu e381 1 1 import java.util.Scanner; 2 3 r oduc e. 6 t r e p , d o no 7 public class TestAverage1 n l y a 8 { l u se o 4-09-22 du Pers o n 9 202 dent.dcccd.e public static void main(String[] args) stu 10 { 11 1 9 7 1 @ int score1, score2, score3; // Three test e381 scores 12 double average; // Average test score 13 char repeat; // To hold 'y' or 'n' 14 String input; // To hold input 15 16 p r o d ce. System.out.println("This program calculates the u o t re " + 17 y, d o n"average of three test scores."); l u s e o n l 9 -2 2 du a Person 18 2024-0dent.dcccd.e stu 19 // Create a Scanner object for keyboard input. 20 1 9 7 1 @ Scanner keyboard = new Scanner(System.in); 21 22 e381 // Get as many sets of test scores as the user wants. 23 do 24 { 25 // Get the first test score in this set. 26 System.out.print("Enter score #1: "); 27 score1 = keyboard.nextInt(); p r o d u ce. o t re 28 29 , d o n // Get the second test score in this set. y 30 u se o n l 9 -2 2 System.out.print("Enter score #2: "); l du a 31 Person 2024-0dent.dcccd.e score2 = keyboard.nextInt(); stu 32 33 1 9 7 1 @ // Get the third test score in this set. 34 35 e381 System.out.print("Enter score #3: "); score3 = keyboard.nextInt(); 36 37 // Consume the remaining newline. 38 keyboard.nextLine(); 39 40 // Calculate and print the average test score. r o duc e. 41 r e p average = (score1 + score2 + score3) / 3.0; 42 n l , d o not System.out.println("The average is " + y a u s e o -0 9 -2 2 average); l du Perso n 43 2024 dent.dcccd.e System.out.println(); // Prints a blank line stu 44 9 7 1 @ e3811 45 // Does the user want to average another set? 46 System.out.println("Would you like to average " + 47 "another set of test scores?"); 48 System.out.print("Enter Y for yes or N for no: "); 49 input = keyboard.nextLine(); // Read a line. 50 repeat = input.charAt(0); p r o d u ce. // Get the first o t re char. 51 , d o n 52 l u s e o n l y 9 -2 2 } while (repeat == 'Y' || repeat == 'y'); du a Person 53 } 2024-0dent.dcccd.e stu 54 } 9 7 1 @ e3811 Program Output with Example Input Shown in Bold This program calculates the average of three test scores. Enter score #1: 89 [Enter] p r o d u ce. Enter score #2: 90 [Enter] , d o n o t re o n l y 9 -2 2 Enter score #3: 97 [Enter] u se a l 24-0 nt.dcccd.edu The average is 92.0 P e rson 2 0 s Would you like to average another @ deof test scores? tuset 9 7 Enter Y for yes or N1for 1 38781[Enter] no: y [Enter] Enter score e #1: Enter score #2: 65 [Enter] Enter score #3: 88 [Enter] The average is 77.0 Would you like to average another set of test scores? Enter Y for yes or N for no: n [Enter] p r o d u ce. , d o n o t re l u s e o n l y 9 -2 2 du a Person 2024-0dent.dcccd.e 9 7 1 @ stu e381 1 When this program was written, the programmer had no way of knowing the number of times the loop would iterate. This is because the loop asks the user whether he or she wants to repeat the process. This type of loop is known as a user controlled loop  , because it allows the user to decide the number of iterations. p r o d u ce. , d o n o t re l u s e o n l y 9 -2 2 du e r s o n a 0 2 4 - 0 c c cd.e P 2 d ent.d s tu 3 8 1 1 9 71@ e p r o d u ce. , d o n o t re l u se o n l y 9 -2 2 du e r s o n a 0 2 4 - 0 c c cd.e P 2 d ent.d s tu 3 8 1 1 9 71@ e r o duc e. not r e p l y, d o a l u s e o n -0 9 -2 2 du Perso n 2024 dent.dcccd.e 9 7 1 @ stu e3811 p r o d u ce. , d o n o t re l u s e o n l y 9 -2 2 du a Person 2024-0dent.dcccd.e 9 7 1 @ stu e3811 4.5: The for Loop r o d u c e. d o n o t re p u s e o nly,for performing -22 a known e r s o CONCEPT: The n a lfor loop is 0 2 4 ideal - 0 9 cc d. e du of iterations. number P 2 d ent.d c s t u @ of loops: conditional loops and count-controlled 3 8 1 1 9 71categories e In general, there are two  loops. A conditional loop executes as long as a particular condition exists. For example, an input validation loop executes as long as the input value is invalid. When you write a conditional loop, you have no way of knowing the number of times it will iterate. Sometimes you do know the exact number of iterations that a loop must perform. A loop e p r o uce. that repeats a specific number of times is known as a count-controlled loop . For d l y, d o not r example, if a loop asks the user to enter the sales amounts for each month in the year, it u s e o n counts to-122and 2 l 9 du will iterate 12 times. In essence, the loop asks the user to enter a sales e r so n a 0 2 4 - 0 c c d.e P 2 ent.dc amount each time it makes a count. s tu d 8 1 1 9 7 1@ A count-controlled e3loop must possess three elements: 1. It must initialize a control variable to a starting value. 2. It must test the control variable by comparing it to a maximum value. When the control variable reaches its maximum value, the loop terminates. 3. It must update the control variable during each iteration. This is usually done by p r o d u ce. o t re incrementing the variable. , d o n l u s e o n l y 9 -2 2 u P erson In Java, the for loop is ideal for a writing 2 024-0 loops. count-controlled c c c d.ed It is specifically d designed to initialize, test, and update a loop control variable.tu @ s deis nthet.format of the for loop 71 Here when used to repeat a single3 e 8 1 1 statement: 9 for (Initialization; Test; Update) Statement; p r o d u ce. d o n o t re e The format of the for loop when , onlyused to9repeat a l u s - 2 2 a block is as follows: du Person 2024-0dent.dcccd.e 9 7 1 @ stu e3811 e38 for (Initialization; Test; Update) { Statement; Statement; // Place as many statements here as necessary. } p r o d u ce. , d o n o t re u s e o n l y 9 -2 2 sofor Peofrthe a l n loop is known 20as24 -0 d c c c d.edu for, there are The first line s tu d ent. the loop header. After the keyword @ 71 separated by semicolons. (Notice there is not a e38119 three expressions inside the parentheses, semicolon after the third expression.) The first expression is the initialization expression. It is normally used to initialize a control variable to its starting value. This is the first action performed by the loop, and it is done only once. The second expression is the test expression. This is a boolean expression that controls the execution of the loop. As long as this expression is true, the body of the for loop will repeat. The for loop is a pretest r o d u ce. loop, so it evaluates the test expression before each iteration. The third expression is the n o t repis a statement update expression. It executes at the end of each iteration. Typically, this d o that increments the loop’s control variable. only, r so n a l use 24-09-22 ccd.edu Pe 20 d e n t.dc Here is an example of a simple for loop that@ 1 tu s “Hello” five times: 1 1 9 7 prints e38 for (count = 1; count

Use Quizgecko on...
Browser
Browser