Archive for October, 2007

Chapter 5 Control Structures: Part 2 213 Fig.

Wednesday, October 31st, 2007

Chapter 5 Control Structures: Part 2 213 Fig. 5.7 An example using switch(part 3 of 3). Line 11 in applet SwitchTestdefines instance variable choiceof type int. This variable stores the user s input that determines which type of shape to draw in paint. Method init(lines 14 26) declares local variable inputof type Stringin line 16. This variable stores the Stringthe user types in the input dialog. Lines 19 22 display the input dialog with staticmethod JOptionPane.showInputDialogand prompt the user to enter 1to draw lines, 2to draw rectangles or 3to draw ovals. Line 25 converts input from a Stringto an intand assigns the result to choice. Method paint (lines 29 62) contains a for structure (lines 35 60) that loops 10 times. In this example, the forstructure s header, in line 35, uses zero-based counting. The values of i for the 10 iterations of the loop are 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9, and the loop terminates when i s value becomes 10. [Note: As you know, the applet container calls method paint after methods init and start. The applet container also calls method paint whenever the applet s screen area must be refreshed e.g., after another window that covered the applet s area is moved to a different location on the screen.] Nested in the for structure s body is a switch structure (lines 38 58) that draws shapes based on the integer value input by the user in method init. The switchstructure consists of a series of case labels and an optional default case. When the flow of control reaches the switch structure, the program evaluates the controlling expression (choice) in the parentheses following keyword switch. The program compares the value of the controlling expression (which must evaluate to an integral value of type byte, char, short or int) with each case label. Assume that the user entered the integer 2as his or her choice. The program compares 2with each casein the switch. If a match occurs (case2:), the program executes the statements for that case. For the integer 2, lines 44 47 draw a rectangle, using four arguments, representing the upper left x-coordinate, upper left y-coordinate, width and height of the rectangle, and the switchstructure exits immediately with the breakstatement. Then, the program increments the counter variable in the forstructure and reevaluates the loop-continuation condition to determine whether to perform another iteration of the loop. The breakstatement causes program control to proceed with the first statement after the switchstructure. (In this case, we reach the end of the forstructure s body, so con Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

212 Control Structures: Part 2 Chapter 5 (Web site hosting) 54

Tuesday, October 30th, 2007

212 Control Structures: Part 2 Chapter 5 54 default: 55 g.drawString( “Invalid value entered”, 56 10, 20 + i * 15 ); 57 58 } // end switch structure 59 60 } // end for structure 61 62 } // end paint method 63 64 } // end class SwitchTest Fig. 5.7 An example using switch(part 2 of 3). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Chapter 5 Control Structures: Part 2 211 1 (Cheapest web hosting)

Tuesday, October 30th, 2007

Chapter 5 Control Structures: Part 2 211 1 // Fig. 5.7: SwitchTest.java 2 // Drawing lines, rectangles or ovals based on user input. 3 4 // Java core packages import java.awt.Graphics; 6 7 // Java extension packages 8 import javax.swing.*; 9 public class SwitchTest extends JApplet { 11 int choice; // user’s choice of which shape to draw 12 13 // initialize applet by obtaining user’s choice 14 public void init() { 16 String input; // user’s input 17 18 // obtain user s choice 19 input = JOptionPane.showInputDialog( “Enter 1 to draw linesn” + 21 “Enter 2 to draw rectanglesn” + 22 “Enter 3 to draw ovalsn” ); 23 24 // convert user’s input to an int choice = Integer.parseInt( input ); 26 } 27 28 // draw shapes on applet’s background 29 public void paint( Graphics g ) { 31 // call inherited version of method paint 32 super.paint( g ); 33 34 // loop 10 times, counting from 0 through 9 for ( int i = 0; i < 10; i++ ) { 36 37 // determine shape to draw based on user’s choice 38 switch ( choice ) { 39 case 1: 41 g.drawLine( 10, 10, 250, 10 + i * 10 ); 42 break; // done processing case 43 44 case 2: g.drawRect( 10 + i * 10, 10 + i * 10, 46 50 + i * 10, 50 + i * 10 ); 47 break; // done processing case 48 49 case 3: g.drawOval( 10 + i * 10, 10 + i * 10, 51 50 + i * 10, 50 + i * 10 ); 52 break; // done processing case 53 Fig. 5.7 An example using switch(part 1 of 3). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Web site template - 210 Control Structures: Part 2 Chapter 5 Notice

Monday, October 29th, 2007

210 Control Structures: Part 2 Chapter 5 Notice that the variables amount, principal and rateare of type double. We did this for simplicity, because we are dealing with fractional parts of dollars and thus need a type that allows decimal points in its values. Unfortunately, this setting can cause trouble. Here is a simple explanation of what can go wrong when using floator double to represent dollar amounts (assuming that dollar amounts are displayed with two digits to the right of the decimal point): Two double dollar amounts stored in the machine could be 14.234 (which would normally be rounded to 14.23 for display purposes) and 18.673 (which would normally be rounded to 18.67 for display purposes). When these amounts are added, they produce the internal sum 32.907, which would normally be rounded to 32.91 for display purposes. Thus, your printout could appear as 14.23 + 18.67 32.91 but a person adding the individual numbers as printed would expect the sum to be 32.90. You have been warned! Good Programming Practice 5.10 Do not use variables of type float or double to perform precise monetary calculations. The imprecision of floating-point numbers can cause errors that will result in incorrect monetary values. In the exercises, we explore the use of integers to perform monetary calculations. [Note: Some third-party vendors provide for-sale class libraries that perform precise monetary calculations.] Note that the body of the forstructure contains the calculation 1.0+rate, which appears as an argument to the Math.pow method. In fact, this calculation produces the same result each time through the loop, so repeating the calculation every iteration of the loop is wasteful. Performance Tip 5.1 Avoid placing expressions whose values do not change inside loops. But even if you do, many of today s sophisticated optimizing compilers will place such expressions outside loops in the generated compiled code. Performance Tip 5.2 Many compilers contain optimization features that improve the code that you write, but it is still better to write good code from the start. 5.5 The switch Multiple-Selection Structure We have discussed the if single-selection structure and the if/else double-selection structure. Occasionally, an algorithm contains a series of decisions in which the algorithm tests a variable or expression separately for each of the constant integral values (i.e., values of types byte, short, int and char) the variable or expression may assume and takes different actions based on those values. Java provides the switch multiple-selection structure to handle such decision making. The applet of Fig. 5.7 demonstrates drawing lines, rectangles or ovals, based on an integer the user inputs via an input dialog. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Web hosting india - Chapter 5 Control Structures: Part 2 209 the

Sunday, October 28th, 2007

Chapter 5 Control Structures: Part 2 209 the currency values should be displayed starting with a dollar sign ($), use a decimal point to separate dollars and cents and use a comma to delineate thousands (e.g., $1,234.56). Class Locale provides constants that can be used to customize this program to represent currency values for other countries, so that currency formats are displayed properly for each locale (i.e., each country s local-currency format). Class NumberFormat (imported at line 5) is located in package java.text, and class Locale (imported at line 6) is located in package java.util. Line 25 declares JTextArea reference outputTextArea and initializes it with a new object of class JTextArea (from package javax.swing). A JTextArea is a GUI component that can display many lines of text. The message dialog that displays the JTextArea determines the width and height of the JTextArea, based on the String it contains. We introduce this GUI component now because we will see many examples throughout the text in which the program outputs contain too many lines to display on the screen. This GUI component allows us to scroll through the lines of text so we can see all the program output. The methods for placing text in a JTextArea include setText and append. Line 28 uses JTextArea method setText to place a Stringin the JTextArea to which outputTextArea refers. Initially, a JTextArea contains an empty String (i.e., a String with no characters in it). The preceding statement replaces the empty String with one containing the column heads for our two columns of output Year and AmountonDeposit. The column heads are separated with a tab character (escape sequence t). Also, the string contains the newline character (escape sequence n), indicating that any additional text appended to the JTextAreashould begin on the next line. The for structure (lines 31 40) executes its body 10 times, varying control variable yearfrom 1 to 10 in increments of 1. (Note that year represents n in the statement of the problem.) Java does not include an exponentiation operator. Instead, we use static method pow of class Math for this purpose. Math.pow(x,y) calculates the value of x raised to the yth power. Method pow takes two arguments of type doubleand returns a double value. Line 34 performs the calculation from the statement of the problem, a = p (1 + r) n where a is amount, p is principal, r is rate and n is year. Lines 37 38 append more text to the end of the outputTextArea. The text includes the current value of year, a tab character (to position to the second column), the result of the method call moneyFormat.format( amount ) which formats the amount as U. S. currency and a newline character (to position the cursor in the JTextArea at the beginning of the next line). Lines 43 44 display the results in a message dialog. Until now, the message displayed has always been a String. In this example, the second argument is outputText- Area a GUI component. An interesting feature of class JOptionPane is that the message it displays with showMessageDialogcan be a Stringor a GUI component, such as a JTextArea. In this example, the message dialog sizes itself to accommodate the JTextArea. We use this technique several times early in this chapter to display large text- based outputs. Later in this chapter, we demonstrate how to add a scrolling capability to the JTextArea, so the user can view a program s output that is too large to display in full on the screen. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

208 Control Structures: Part 2 Chapter 5 24 (Unable to start debugging on the web server)

Sunday, October 28th, 2007

208 Control Structures: Part 2 Chapter 5 24 // create JTextArea to display output 25 JTextArea outputTextArea = new JTextArea(); 26 27 // set first line of text in outputTextArea 28 outputTextArea.setText( “YeartAmount on depositn” ); 29 30 // calculate amount on deposit for each of ten years 31 for ( int year = 1; year <= 10; year++ ) { 32 33 // calculate new amount for specified year 34 amount = principal * Math.pow( 1.0 + rate, year ); 35 36 // append one line of text to outputTextArea 37 outputTextArea.append( year + “t” + 38 moneyFormat.format( amount ) + “n” ); 39 40 } // end for structure 41 42 // display results 43 JOptionPane.showMessageDialog( null, outputTextArea, 44 “Compound Interest”, JOptionPane.INFORMATION_MESSAGE ); 45 46 System.exit( 0 ); // terminate the application 47 48 } // end method main 49 50 } // end class Interest Fig. 5.6 Calculating compound interest with the forstructure (part 2 of 2). Line 17 in method main declares three double variables and initializes two of them principal to 1000.0 and rate to .05. Java treats floating-point constants, like 1000.0 and .05 in Fig. 5.6, as type double. Similarly, Java treats whole number constants, like 7 and -22, as type int. Lines 21 22 declare NumberFormat reference moneyFormat and initialize it by calling static method getCurrencyInstance of class NumberFormat. This method returns a NumberFormatobject that can format numeric values as currency (e.g., in the United States, currency values normally are preceded with a dollar sign, $). The argument to the method Locale.US indicates that Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Chapter 5 Control Structures: Part 2 207 Similarly, (Web server application)

Saturday, October 27th, 2007

Chapter 5 Control Structures: Part 2 207 Similarly, the initialization sum =0 could be merged into the initialization section of the forstructure. Good Programming Practice 5.8 Although statements preceding a for structure and statements in the body of a for structure can often be merged into the header of the for structure, avoid doing so, because it makes the program more difficult to read. Good Programming Practice 5.9 Limit the size of control structure headers to a single line. if possible. The next example uses the forstructure to compute compound interest. Consider the following problem: A person invests $1000.00 in a savings account yielding 5% interest. Assuming that all interest is left on deposit, calculate and print the amount of money in the account at the end of each year for 10 years. Use the following formula to determine the amounts: a = p (1 + r) n where p is the original amount invested (i.e., the principal) r is the annual interest rate n is the number of years a is the amount on deposit at the end of the nth year. This problem involves a loop that performs the indicated calculation for each of the 10 years the money remains on deposit. The solution is the application shown in Fig. 5.6. 1 // Fig. 5.6: Interest.java 2 // Calculating compound interest 3 4 // Java core packages 5 import java.text.NumberFormat; 6 import java.util.Locale; 7 8 // Java extension packages 9 import javax.swing.JOptionPane; 10 import javax.swing.JTextArea; 11 12 public class Interest { 13 14 // main method begins execution of Java application 15 public static void main( String args[] ) 16 { 17 double amount, principal = 1000.0, rate = 0.05; 18 19 // create DecimalFormat to format floating-point numbers 20 // with two digits to the right of the decimal point 21 NumberFormat moneyFormat = 22 NumberFormat.getCurrencyInstance( Locale.US ); 23 Fig. 5.6 Calculating compound interest with the forstructure (part 1 of 2). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

206 Control Structures: Part 2 Chapter 5 Common (Free web host)

Friday, October 26th, 2007

206 Control Structures: Part 2 Chapter 5 Common Programming Error 5.6 Not using the proper relational operator in the loop-continuation condition of a loop that counts downward (such as using i<=1in a loop counting down to 1) is usually a logic error and will yield incorrect results when the program runs. The next two sample programs demonstrate simple applications of the forrepetition structure. The application in Fig. 5.5 uses the for structure to sum all the even integers from 2to 100. Remember that the javainterpreter is used to execute an application from the command window. Note that the body of the for structure in Fig. 5.5 could actually be merged into the rightmost portion of the forheader by using a comma as follows: for ( int number = 2; number <= 100; sum += number, number += 2 ) ; // empty statement 1 // Fig. 5.5: Sum.java 2 // Counter-controlled repetition with the for structure 3 4 // Java extension packages 5 import javax.swing.JOptionPane; 6 7 public class Sum { 8 9 // main method begins execution of Java application 10 public static void main( String args[] ) 11 { 12 int sum = 0; 13 14 // sum even integers from 2 through 100 15 for ( int number = 2; number <= 100; number += 2 ) 16 sum += number; 17 18 // display results 19 JOptionPane.showMessageDialog( null, “The sum is ” + sum, 20 “Sum Even Integers from 2 to 100″, 21 JOptionPane.INFORMATION_MESSAGE ); 22 23 System.exit( 0 ); // terminate the application 24 25 } // end method main 26 27 } // end class Sum Fig. 5.5Summation with the forstructure. Fig. 5. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Space web hosting - Chapter 5 Control Structures: Part 2 205 Note

Friday, October 26th, 2007

Chapter 5 Control Structures: Part 2 205 Note that, besides small circles and arrows, the flowchart contains only rectangle symbols and a diamond symbol. The programmer fills the rectangles and diamonds with actions and decisions appropriate to the algorithm. 5.4 Examples Using the forStructure The examples given next show methods of varying the control variable in a forstructure. In each case, we write the appropriate for structure header. Note the change in the relational operator for loops that decrement the control variable. a) Vary the control variable from 1to 100in increments of 1. for ( int i = 1; i <= 100; i++ ) b) Vary the control variable from 100 to 1in increments of -1(i.e., decrements of 1). for ( int i = 100; i >= 1; i– ) c) Vary the control variable from 7to 77in steps of 7. for ( int i = 7; i <= 77; i += 7 ) d) Vary the control variable from 20to 2in steps of -2. for ( int i = 20; i >= 2; i -= 2 ) e) Vary the control variable over the following sequence of values: 2, 5, 8, 11, 14, 17, 20. for ( int j = 2; j <= 20; j += 3 ) f) Vary the control variable over the following sequence of values: 99, 88, 77, 66, 55, 44, 33, 22, 11, 0. for ( int j = 99; j >= 0; j -= 11 ) counter <= 10 g.drawLine( 10, 10, 250, counter * 10 ); true false int counter = 1 counter++ Establish initial value of control variable. Determine if final value of control variable has been reached. Body of loop (this may be many statements) Increment the control variable. Fig. 5.4Flowcharting a typical forrepetition structure. Fig. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

My space web page - 204 Control Structures: Part 2 Chapter 5 counter

Thursday, October 25th, 2007

204 Control Structures: Part 2 Chapter 5 counter = counter + 1 counter += 1 ++counter counter++ are equivalent in the increment portion of the for structure. Many programmers prefer the form counter++, because a for structure increments its control variable after the body of the loop executes and placing ++ after the variable name increments the variable after the program uses its value. Therefore, the postincrementing form seems more natural. Preincrementing and postincrementing have the same effect in the increment expression, because the increment does not appear in a larger expression. The two semicolons in the for structure are required. Common Programming Error 5.4 Using commas instead of the two required semicolons in a for header is a syntax error. Common Programming Error 5.5 Placing a semicolon immediately to the right of the right parenthesis of a for header makes the body of that for structure an empty statement. This is normally a logic error. The initialization, loop-continuation condition and increment portions of a for structure can contain arithmetic expressions. For example, assume that x=2 and y=10. If x and y are not modified in the body of the loop, the statement for ( int j = x; j <= 4 * x * y; j += y / x ) is equivalent to the statement for ( int j = 2; j <= 80; j += 5 ) The increment of a forstructure may also be negative, in which case it is really a decrement, and the loop actually counts downward. If the loop-continuation condition is initially false, the program does not perform the body of the for structure. Instead, execution proceeds with the statement following the for structure. Programs frequently display the control variable value or use it in calculations in loop body. However, this use is not required. It is common to use the control variable for controlling repetition while never mentioning it in the body of the for structure. Testing and Debugging Tip 5.1 Although the value of the control variable can be changed in the body of a for loop, avoid doing so, because this practice can lead to subtle errors. We flowchart the for structure much as we do the while structure. For example, the flowchart of the for statement for ( int counter = 1; counter <= 10; counter++ ) g.drawLine( 10, 10, 250, counter * 10 ); is shown in Fig. 5.4. This flowchart makes it clear that the initialization occurs only once and that the increment occurs each time after the program performs the body statement. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01