Archive for October, 2007

Cheap web hosting - Chapter 5 Control Structures: Part 2 203 The

Wednesday, October 24th, 2007

Chapter 5 Control Structures: Part 2 203 The general format of the for structure is for ( expression1; expression2; expression3 ) statement where expression1 names the loop s control variable and provides its initial value, expression2 is the loop-continuation condition (containing the control variable s final value) and expression3 modifies the value of the control variable, so that the loop-continuation condition eventually becomes false. In most cases, the for structure can be represented with an equivalent while structure, with expression1, expression2 and expression3 placed as follows: expression1; while ( expression2 ) { statement expression3; } In Section 5.7, we show a case in which a for structure cannot be represented with an equivalent while structure. If expression1 (the initialization section) declares the control variable inside the parentheses of the header of the forstructure (i.e., the control variable s type is specified before the name of the variable), the control variable can be used only in the for structure. This restricted use of the name of the control variable is known as the variable s scope. The scope of a variable defines where the program can use the variable. For example, we mentioned previously that a program can use a local variable only in the method that declares the variable. Scope is discussed in detail in Chapter 6, Methods. Common Programming Error 5.3 When the control variable of a for structure is initially defined in the initialization section of the header of the for structure, using the control variable after the body of the structure is a syntax error. Sometimes, expression1 and expression3 in a for structure are comma-separated lists of expressions that enable the programmer to use multiple initialization expressions and/or multiple increment expressions. For example, there may be several control variables in a single for structure that must be initialized and incremented. Good Programming Practice 5.7 Place only expressions involving the control variables in the initialization and increment sections of a for structure. Manipulations of other variables should appear either before the loop (if they execute only once, like initialization statements) or in the body of the loop (if they execute once per iteration of the loop, like incrementing or decrementing statements). The three expressions in the for structure are optional. If expression2 is omitted, Java assumes that the loop-continuation condition is true, thus creating an infinite loop. One might omit expression1 if the program initializes the control variable before the loop. One might omit expression3 if the program calculates the increment with statements in the loop s body or if the loop does not require an increment. The increment expression in the for structure acts as a stand-alone statement at the end of the body of the for structure, so the expressions Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Best web hosting - 202 Control Structures: Part 2 Chapter 5 The

Wednesday, October 24th, 2007

202 Control Structures: Part 2 Chapter 5 The applet s paint method operates as follows: When the for structure (lines 20 21) begins executing, the control variable counteris initialized to 1. (The first two elements of counter-controlled repetition and the name of the control variable and its initial value.) Next, the program checks the loop-continuation condition, counter<=10. The condition contains the final value (10) of the control variable. Because the initial value of counteris 1, the condition is satisfied (true), so the body statement (line 21) draws a line. After executing the body of the loop, the program increments variable counter in the expression counter++. Then, the program performs the loop-continuation test again to determine whether the program should continue with the next iteration of the loop or whether it should terminate the loop. At this point, the control variable value is 2, so the condition is true (i.e., the final value is not exceeded), and thus the program performs the body statement again (i.e., the next iteration of the loop). This process continues until the counter s value becomes 11, causing the loop-continuation test to fail and repetition to terminate. Then, the program performs the first statement after the for structure. (In this case, method paintterminates, because the program reaches the end of paint.) Notice that Fig. 5.2 uses the loop-continuation condition counter<=10. If the programmer incorrectly specified counter < 10 as the condition, the loop would be executed only nine times. This mistake is a common logic error called an off-by-one error. Common Programming Error 5.2 Using an incorrect relational operator or using an incorrect final value of a loop counter in the condition of a while, for or do/while structure can cause an off-by-one error. Good Programming Practice 5.6 Using the final value in the condition of a while or for structure and using the <= relational operator will help avoid off-by-one errors. For a loop that prints the values 1 to 10, the loop-continuation condition should be counter <= 10 rather than counter < 10 (which causes an off-by-one error) or counter < 11 (which is correct). Many programmers prefer so-called zero-based counting, in which to count 10 times, counter would be initialized to zero and the loop-continuation test would be counter < 10. Figure 5.3 takes a closer look at the forstructure of Fig. 5.2. The forstructure s first line (including the keyword for and everything in parentheses after for) is sometimes called the for structure header. Notice that the for structure does it all : It specifies each of the items needed for counter-controlled repetition with a control variable. If there is more than one statement in the body of the forstructures, braces ({and }) are required to define the body of the loop. forkeyword Control variable name Final value of control variable for ( int counter = 1; counter <= 10; counter++ ) Initial value of control variable Increment of control variable Loop-continuation condition Fig. 5.3Components of a typical forstructure header. Fig. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Chapter 5 Control (Web file server) Structures: Part 2 201 Good

Tuesday, October 23rd, 2007

Chapter 5 Control Structures: Part 2 201 Good Programming Practice 5.5 Vertical spacing above and below control structures, and indentation of the bodies of control structures within the control structures headers, gives programs a two-dimensional appearance that enhances readability. 5.3 The forRepetition Structure The for repetition structure handles all of the details of counter-controlled repetition. To illustrate the power of the for structure, let us rewrite the applet of Fig. 5.1. The result is shown in Fig. 5.2. Remember that this program requires a separate HTML document to load the applet into the appletviewer. For the purpose of this applet, the tag specifies a width of 275pixels and a height of 110pixels. 1 // Fig. 5.2: ForCounter.java 2 // Counter-controlled repetition with the for structure 3 4 // Java core packages 5 import java.awt.Graphics; 6 7 // Java extension packages 8 import javax.swing.JApplet; 9 10 public class ForCounter extends JApplet { 11 12 // draw lines on applet s background 13 public void paint( Graphics g ) 14 { 15 // call inherited version of method paint 16 super.paint( g ); 17 18 // Initialization, repetition condition and incrementing 19 // are all included in the for structure header. 20 for ( int counter = 1; counter <= 10; counter++ ) 21 g.drawLine( 10, 10, 250, counter * 10 ); 22 23 } // end method paint 24 25 } // end class ForCounter Fig. 5.2Counter-controlled repetition with the forstructure. Fig. 5. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Web server logs - 200 Control Structures: Part 2 Chapter 5 Line

Monday, October 22nd, 2007

200 Control Structures: Part 2 Chapter 5 Line 21 in the while structure uses Graphics reference g, which refers to the applet s Graphics object, to send the drawLine message to the Graphics object, asking it to draw a line. Remember that sending a message to an object actually means calling a method to perform a task. One of the Graphics object s many services is to draw lines. In previous chapters, we also saw that the Graphics object s other services include drawing rectangles, strings and ovals. Graphics method drawLine requires four arguments, representing the line s first x-coordinate, first y-coordinate, second x-coordinate and second y-coordinate. In this example, the second y-coordinate changes value during each iteration of the loop with the calculation counter*10. This change causes the second point (the end point of the line) in each call to drawLineto move 10 pixels down the applet s display area. Line 22 in the while structure increments the control variable by 1 for each iteration of the loop. The loop-continuation condition in the while structure tests whether the value of the control variable is less than or equal to 10 (the final value for which the condition is true). Note that the program performs the body of this while structure even when the control variable is 10. The loop terminates when the control variable exceeds 10 (i.e., counter becomes 11). The program in Fig. 5.1 can be made more concise by initializing counterto 0 and preincrementing counterin the while structure condition as follows: while ( ++counter <= 10 ) // repetition condition g.drawLine( 10, 10, 250, counter * 10 ); This code saves a statement (and eliminates the need for braces around the loop s body), because the while condition performs the increment before testing the condition. (Remember that the precedence of ++is higher than that of <=.) Coding in such a condensed fashion takes practice. Good Programming Practice 5.1 Programs should control counting loops with integer values. Common Programming Error 5.1 Because floating-point values may be approximate, controlling the counting of loops with floating-point variables may result in imprecise counter values and inaccurate tests for termination. Good Programming Practice 5.2 Indent the statements in the body of each control structure. Good Programming Practice 5.3 Put a blank line before and after each major control structure to make it stand out in the pro- gram. Good Programming Practice 5.4 Too many levels of nesting can make a program difficult to understand. As a general rule, try to avoid using more than three levels of nesting. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Professional web hosting - Chapter 5 Control Structures: Part 2 199 1

Sunday, October 21st, 2007

Chapter 5 Control Structures: Part 2 199 1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition 3 4 // Java core packages 5 import java.awt.Graphics; 6 7 // Java extension packages 8 import javax.swing.JApplet; 9 10 public class WhileCounter extends JApplet { 11 12 // draw lines on applet s background 13 public void paint( Graphics g ) 14 { 15 // call inherited version of method paint 16 super.paint( g ); 17 18 int counter = 1; // initialization 19 20 while ( counter <= 10 ) { // repetition condition 21 g.drawLine( 10, 10, 250, counter * 10 ); 22 ++counter; // increment 23 24 } // end while structure 25 26 } // end method paint 27 28 } // end class WhileCounter Fig. 5.1Counter-controlled repetition. Fig. 5. The applet s paint method (that the applet container calls when it executes the applet) operates as follows: The declaration on line 18 names the control variable (counter), declares it to be an integer, reserves space for it in memory and sets it to an initial value of 1. Declarations that include initialization are, in effect, executable statements. The declaration and initialization of countercould also have been accomplished with the declaration and statement int counter; // declare counter counter = 1; // initialize counter to 1 The declaration is not executable, but the assignment statement is. We use both methods of initializing variables throughout this book. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

198 Control (Starting a web site) Structures: Part 2 Chapter 5 Outline

Sunday, October 21st, 2007

198 Control Structures: Part 2 Chapter 5 Outline 5.1 Introduction 5.2 Essentials of Counter-Controlled Repetition 5.3 The for Repetition Structure 5.4 Examples Using the for Structure 5.5 The switch Multiple-Selection Structure 5.6 The do/while Repetition Structure 5.7 Statements break and continue 5.8 Labeled break and continue Statements 5.9 Logical Operators 5.10 Structured Programming Summary 5.11 (Optional Case Study) Thinking About Objects: Identifying Objects States and Activities Summary Terminology Self-Review Exercises Answers to Self-Review Exercises Exercises 5.1 Introduction Chapter 4 began our introduction to the types of building blocks that are available for problem solving and used those building blocks to employ proven program construction principles. In this chapter, we continue our presentation of the theory and principles of structured programming by introducing Java s remaining control structures. As in Chapter 4, the Java techniques you learn here are applicable to most high-level languages. When we begin our formal treatment of object-based programming in Java in Chapter 8, we will see that the control structures we study in this chapter and Chapter 4 are helpful in building and manipulating objects. 5.2 Essentials of Counter-Controlled Repetition Counter-controlled repetition requires the following: 1. the name of a control variable (or loop counter), 2. the initial value of the control variable, 3. the amount of increment (or decrement) by which the control variable is modified each time through the loop (also known as each iteration of the loop), and 4. the condition that tests for the final value of the control variable (i.e., whether looping should continue). To see the four elements of counter-controlled repetition, consider the applet shown in Fig. 5.1, which draws 10 lines from the applet s paint method. Remember that an applet requires a separate HTML document to load the applet into the appletviewer or a browser. For the purpose of this applet, the tag specifies a width of 275 pixels and a height of 110 pixels. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

5 Control Structures: Part 2 Objectives To (Bulletproof web design)

Saturday, October 20th, 2007

5 Control Structures: Part 2 Objectives To be able to use the forand do/while repetition structures to execute statements in a program repeatedly. To understand multiple selection using the switch selection structure. To be able to use the breakand continue program control statements. To be able to use the logical operators. Who can control his fate? William Shakespeare, Othello The used key is always bright. Benjamin Franklin Man is a tool-making animal. Benjamin Franklin Intelligence is the faculty of making artificial objects, especially tools to make tools. Henri Bergson Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

196 Control Structures: Part 1 (Web hosting resellers) Chapter 4 4.30

Friday, October 19th, 2007

196 Control Structures: Part 1 Chapter 4 4.30 Write an application that reads three nonzero integers and determines and prints if they could represent the sides of a right triangle. 4.31 A company wants to transmit data over the telephone, but it is concerned that its phones may be tapped. All of its data are transmitted as four-digit integers. It has asked you to write a program that will encrypt its data so that the data may be transmitted more securely. Your application should read a four-digit integer entered by the user in an input dialog and encrypt it as follows: Replace each digit by (the sum of that digit plus 7) modulus 10. Then swap the first digit with the third, and swap the second digit with the fourth. Then print the encrypted integer. Write a separate application that inputs an encrypted four-digit integer and decrypts it to form the original number. 4.32 The factorial of a nonnegative integer n is written as n! (pronounced n factorial ) and is defined as follows: n! = n (n -1) (n -2) 1 (for valuesof n greater than or equal to 1) and n! = 1 (for n = 0). For example, 5! = 5 4 3 2 1,which is 120. a) Write an application that reads a nonnegative integer from an input dialog and computes and prints its factorial. b) Write an application that estimates the value of the mathematical constant e by using the formula 111 e = 1+—-+—-+—–+ 1! 2! 3! c) Write an application that computes the value of ex by using the formula: 23 e x = 1 + —-x -+-x —-+ x —-+ 1! 2! 3! Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Chapter 4 Control Structures: Part 1 195 Use (Web space)

Friday, October 19th, 2007

Chapter 4 Control Structures: Part 1 195 Use an input dialog to read the size from the user. Your program should work for squares of all lengths of side between 1 and 20. 4.24 A palindrome is a number or a text phrase that reads the same backward as forward. For example, each of the following five-digit integers are palindromes: 12321, 55555, 45554 and 11611. Write an application that reads in a five-digit integer and determines whether or not it is a palindrome. If the number is not five digits long, display an error message dialog indicating the problem to the user. When the user dismisses the error dialog, allow the user to enter a new value. 4.25 Write an application that inputs an integer containing only 0s and 1s (i.e., a binary integer) and prints its decimal equivalent. [Hint: Use the modulus and division operators to pick off the binary number s digits one at a time, from right to left. Just as in the decimal number system, where the rightmost digit has a positional value of 1 and the next digit to the left has a positional value of 10, then 100, then 1000, etc., in the binary number system the rightmost digit has a positional value of 1, the next digit to the left has a positional value of 2, then 4, then 8, etc. Thus, the decimal number 234 can be interpreted as 4 * 1 + 3 * 10 + 2 * 100. The decimal equivalent of binary 1101 is 1 * 1 + 0 * 2 + 1 * 4 + 1 * 8,or 1 +0 + 4 + 8 or,13.] 4.26 Write an application that displays the following checkerboard pattern: ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** Your program may use only three output statements, one of the form System.out.print( “* ” ); one of the form System.out.print( ” ” ); and one of the form System.out.println(); Note that the preceding statement indicates that the program should output a single newline character to drop to the next line of the output. [Hint: Repetition structures are required in this exercise.] 4.27 Write an application that keeps displaying in the command window the multiples of the integer 2, namely 2, 4, 8, 16, 32, 64, etc. Your loop should not terminate (i.e., you should create an infinite loop). What happens when you run this program? 4.28 What is wrong with the following statement? Provide the correct statement to add one to the sum of x and y. System.out.println( ++(x + y) ); 4.29 Write an application that reads three nonzero values entered by the user in input dialogs and determines and prints if they could represent the sides of a triangle. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

194 Control Structures: Part 1 Chapter 4 b) (Web hosting top)

Thursday, October 18th, 2007

194 Control Structures: Part 1 Chapter 4 b) if ( x < 10 ) { if ( y > 10 ) System.out.println( “*****” ); } else { System.out.println( “#####” ); System.out.println( “$$$$$” ); } 4.22 (Another Dangling-Else Problem) Modify the given code to produce the output shown in each part of the problem. Use proper indentation techniques. You may not make any changes other than inserting braces and changing the indentation of the code. The compiler ignores indentation in a Java program. We have eliminated the indentation from the given code to make the problem more challenging. [Note: It is possible that no modification is necessary for some of the parts.] if ( y == 8 ) if ( x == 5 ) System.out.println( “@@@@@” ); else System.out.println( “#####” ); System.out.println( “$$$$$” ); System.out.println( “&&&&&” ); a) Assuming that x=5 and y=8, the following output is produced: @@@@@ $$$$$ &&&&& b) Assuming that x=5 and y=8, the following output is produced: @@@@@ c) Assuming that x=5 and y=8, the following output is produced: @@@@@ &&&&& d) Assuming that x=5 and y=7, the following output is produced [Note: The last three output statements after the else are all part of a block]:] ##### $$$$$ &&&&& 4.23 Write an applet that reads in the size of the side of a square and displays a hollow square of that size out of asterisks, by using the drawString method inside your applet s paint method. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01