simplyjava1_06

simplyjava1_06 - 6 T Outline Test-Driving the Wage...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 6 T Outline Test-Driving the Wage Calculator Application 6.2 Algorithms 6.3 Pseudocode 6.4 Control Statements 6.5 if Selection Statement 6.6 if…else Selection Statement 6.7 Constructing the Wage Calculator Application 6.8 Assignment Operators 6.9 Formatting Text 6.10 Using the Debugger: The print and set Commands 6.11 Wrap-Up 6.1 114 T O R I A L Wage Calculator Application Objectives In this tutorial, you will learn to: s Use basic problem-solving techniques. s Use structured programming techniques. s Use control statements. s Use pseudocode as an application development tool. s Use the if and if…else selection statements to choose between alternative actions. s Use the assignment operators. s Use the debugger’s print command to evaluate expressions. s Use the debugger’s set command to change variable values during program execution. U Introducing Algorithms, Pseudocode and Program Control B efore you write an application, it is essential to have a thorough understanding of the problem you need to solve. This will help you carefully plan your approach to finding a solution. When writing an application, it is equally important to recognize the types of building blocks that are available and to use proven application-construction principles. In this tutorial, you will learn the theory and principles of structured programming. Structured programming is a technique for organizing program control to help you develop applications that are easy to understand, debug and modify. The techniques presented are applicable to most high-level languages, including Java. 6.1 Test-Driving the Wage Calculator Application In this tutorial, you will build a Wage Calculator application that enables you to input an employee’s hourly wage and hours worked to calculate the employee’s wages for a week. This application must meet the following requirements: Application Requirements A company needs an application that calculates the gross wages per week for each of its employees. Each employee’s weekly salary is based on the employee’s number of hours worked and hourly wage. A standard work week is 40 hours. Any time worked over 40 hours in a week is considered “overtime,” and employees earn time-and-a-half for the extra hours. Create an application that accepts one employee’s number of hours worked and hourly wage, and calculates the employee’s total (gross) wages for the week. This application calculates gross wages from an employee’s hourly wage and hours worked per week. If an employee has worked 40 or fewer hours, the employee is paid regular wages. The calculation differs if the employee has worked more than the standard 40-hour work week. In this tutorial, you will learn a programming tool known as a control statement that allows you to make this distinction and perform different calculations based on different user inputs. You begin by test-driving the completed Wage Calculator application. Then, you will learn the additional Java technologies you will need to create your own version of this application. Tutorial 6 Test-Driving the Wage Calculator Application Wage Calculator Application 115 1. Locating the completed application. Open the Command Prompt window by selecting Start > Programs > Accessories > Command Prompt. Change to your completed Wage Calculator application directory by typing cd C:\Examples\Tutorial06\CompletedApplication\WageCalculator. 2. Running the Wage Calculator application. Type java WageCalculator in the Command Prompt window to run the application (Fig. 6.1). Figure 6.1 Running the Wage Calculator application. 3. Enter the employee’s hourly wage. Enter 10 in the Hourly wage: JTextField. 4. Enter the number of hours the employee worked. Enter 45 in the Hours worked: JTextField. 5. Calculate the employee’s gross earnings. Click the Calculate JButton. The result ($475.00) is displayed in the Gross wages: output JTextField (Fig. 6.2). Notice that the employee’s wages for one week are the sum of the wages for the standard 40-hour work week (40 * 10) and the overtime pay (5 * 10 * 1.5). Figure 6.2 Calculating wages by clicking the Calculate JButton. 6. Closing the application. Close your running application by clicking its close button. 7. Closing the Command Prompt window. Close the Command Prompt window by clicking its close button. 6.2 Algorithms Computing problems can be solved by executing a series of actions in a specific order. A procedure for solving a problem, in terms of: 1. the actions to be executed and 2. the order in which these actions are to be executed is called an algorithm. The following example demonstrates the importance of correctly specifying the order in which the actions are to be executed. Consider the “rise-and-shine algorithm” followed by one junior executive for getting out of bed and going to work: (1) get out of bed, (2) take off pajamas, (3) take a shower, (4) get 116 Introducing Algorithms, Pseudocode and Program Control Tutorial 6 dressed, (5) eat breakfast and (6) carpool to work. This routine prepares the executive for a productive day at the office. However, suppose that the executive performs the same steps in a slightly different order: (1) get out of bed, (2) take off pajamas, (3) get dressed, (4) take a shower, (5) eat breakfast and (6) carpool to work. In this case, our junior executive shows up for work soaking wet. Program control refers to the task of executing an application’s statements in the correct order. In this tutorial, you will begin to investigate Java’s program-control capabilities. SELF-REVIEW 1. order. refer(s) to the task of executing an application’s statements in the correct a) Actions c) Control statements b) Program control d) GUI design 2. A(n) is a procedure for solving a problem in terms of the actions to be executed and the order in which these actions are to be executed. a) chart c) algorithm b) control statement d) ordered list Answers: 1) b. 2) c. 6.3 Pseudocode Software Design Tip Pseudocode helps you conceptualize an application during the application design process. Pseudocode statements can be converted to Java at a later point. Pseudocode is an informal language that helps you develop algorithms. The pseudocode you will learn is particularly useful in the development of algorithms that will be converted to structured programming portions of Java applications. Pseudocode resembles everyday English; it is convenient and user-friendly, but it is not an actual computer programming language. Pseudocode statements are not executed on computers. Rather, pseudocode helps you “think out” an application before attempting to write it in a programming language, such as Java. In this tutorial, you will see several examples of pseudocode. The style of pseudocode that you will learn consists solely of characters, so you can create and modify pseudocode conveniently by using your text editor. A carefully prepared pseudocode program can be converted easily to a corresponding Java application. Much of this conversion is as simple as replacing pseudocode statements with their Java equivalents. Now let’s look at an example of a pseudocode statement: Assign 0 to the counter This pseudocode statement specifies an easy to understand task. You can put several such statements together to form an algorithm that can be used to meet application requirements. When the pseudocode algorithm has been completed, you can then convert pseudocode statements to their equivalent Java statements. The pseudocode statement above, for instance, can be converted to the following Java statement: counter = 0; Pseudocode normally describes only executable statements, which are the actions that are performed when the corresponding Java application is run. An example of a programming statement that is not executable is a declaration. The declaration int counter; informs the compiler of counter’s type and instructs the compiler to reserve space in memory for this variable. The declaration does not cause any action (such as Tutorial 6 Wage Calculator Application 117 input, output or a calculation) to occur when the application executes, so you would not include this information in the pseudocode even though each variable must be declared before it is used in an application. SELF-REVIEW 1. algorithms. is an artificial and informal language that helps programmers develop a) Pseudocode c) Notation 2. Pseudocode b) Java-Speak d) Executable . a) usually describes only declarations c) usually describes only executable lines of code b) is executed on computers d) usually describes declarations and executable lines of code Answers: 1) a. 2) c. 6.4 Control Statements Normally, statements in an application are executed one after another in the order in which they are written. This is called sequential execution. However, Java allows you to specify that the next statement to be executed might not be the next one in sequence. A transfer of control occurs when the next statement to be executed does not come immediately after the currently executing statement. This is common in computer applications. All applications can be written in terms of only three forms of control: sequence, selection and repetition. Unless directed to act otherwise, the computer executes Java statements sequentially—that is, one after the other in the order in which they appear in the application. The activity diagram in Fig. 6.3 illustrates two statements that execute in sequence. In this case, two calculations are performed in order. The activity diagram presents a graphical representation of the algorithm. add grade to total Corresponding Java statement: total = total + grade; add 1 to counter Corresponding Java statement: counter = counter + 1; Figure 6.3 Sequence statement activity diagram. Activity diagrams are part of the Unified Modeling Language (UML)—an industry standard for modeling software systems. An activity diagram models the activity (also called the workflow) of a portion of a software system. An activity might include a portion of an algorithm, such as the sequence of two statements in Fig. 6.3. Activity diagrams are composed of special-purpose symbols, such as actionstate symbols (rectangles with their left and right sides replaced with arcs curving outward), diamonds and small circles. These symbols are connected by transition arrows, which represent the flow of the activity. Figure 6.3 does not include any diamond symbols—these will be used in later activity diagrams. Like pseudocode, activity diagrams help programmers develop and represent algorithms. Activity diagrams clearly show how control statements operate. 118 Introducing Algorithms, Pseudocode and Program Control Tutorial 6 Consider the activity diagram for the sequence statement in Fig. 6.3. The activity diagram contains two action states, which represent actions to perform. Each action state contains an action expression—for example, “add grade to total” or “add 1 to counter”—which specifies a particular action to perform. Action expressions are similar to pseudocode. The arrows in the activity diagram, called transition arrows, represent transitions, which indicate the order in which the actions represented by the action states occur. The application that implements the activities illustrated by Fig. 6.3 first adds grade to total, then adds 1 to counter. The solid circle located at the top of the activity diagram represents the activity’s initial state—the beginning of the workflow, before the application performs the activities. The solid circle surrounded by a hollow circle that appears at the bottom of the activity diagram represents the final state—the end of the workflow, after the application performs its activities. Notice, in Fig. 6.3, the rectangles with the upper-right corners folded over. These look like sheets of paper and are called notes in the UML. Notes are like comments in Java applications—they are explanatory remarks that describe the purpose of symbols in the diagram. Figure 6.3 uses UML notes to show the Java code that the programmer might associate with each action state in the activity diagram. A dotted line connects each note to the element that the note describes. Activity diagrams normally do not show the Java code that implements the activity, but we use notes here to show you how the diagram relates to Java code. Java provides three types of selection statements, which you will learn in this tutorial and in Tutorial 11. The if statement is a single-selection statement because it selects or ignores a single action to execute. The if…else statement is called a double-selection statement because it selects between two different actions. The switch statement (discussed in Tutorial 11) is called a multiple-selection statement because it selects among many different actions or sequences of actions. Java provides three types of repetition statements—while, do…while and for—to execute statements in an application repeatedly. The while repetition statement is covered in Tutorial 8, do…while is covered in Tutorial 9 and for is covered in Tutorial 10. The words if, else, switch, while, do and for are all Java keywords—Appendix E includes a complete list of Java keywords. Most of Java’s keywords and their uses are discussed throughout this book. So, Java has three forms of control—sequence, selection and repetition. Each Java application is formed by combining as many of each type of control statement as is necessary. Java control statements are single-entry/single-exit control statements—each has one entry point and one exit point. Such control statements make it easy to build applications—the control statements are attached to one another by connecting the exit point of one control statement to the entry point of the next. This is similar to stacking building blocks, so we call it control-statement stacking. The only other way to connect control statements is through control-statement nesting, whereby one control statement is placed inside another. Thus, algorithms in Java applications are constructed from only three forms of control (sequence, selection and repetition) combined in only two ways (stacking and nesting). This is a model of simplicity. SELF-REVIEW 1. All Java applications can be written in terms of a) one c) three types of program control. b) two d) four 2. The process of application statements executing one after another in the order in which they are written is called a) transfer of control c) workflow Answers: 1) c. 2) b. . b) sequential execution d) None of the above. Tutorial 6 Wage Calculator Application 119 6.5 if Selection Statement A selection statement chooses among alternative courses of action in an application. The if selection statement performs (selects) an action based on a condition. A condition is an expression with a true or false value that is used to make a decision. A condition is evaluated (that is, tested) to determine whether its value is true or false. These values are of type boolean and are specified in Java code by using the keywords true and false. Sometimes a condition is referred to as a boolean expression. If the condition evaluates to true, the action specified by the if statement will execute. If the condition evaluates to false, the action specified by the if statement will be skipped. For example, suppose that the passing grade on a test is 60 (out of 100). The pseudocode statement If student’s grade is greater than or equal to 60 Display “Passed” determines whether the condition “student’s grade is greater than or equal to 60” is true or false. If the condition is true, then “Passed” is displayed, and the next pseudocode statement in order is “performed.” (Remember that pseudocode is not a real programming language, so pseudocode “programs” do not actually execute on computers.) If the condition is false, the display statement is ignored, and the next pseudocode statement in order is performed. The preceding pseudocode if statement may be written in Java as if ( studentGrade >= 60 ) { gradeDisplayJLabel.setText( "Passed" ); } Good Programming Practice Always using braces in an if statement helps prevent their accidental omission when the if statement’s body contains more than one statement. Good Programming Practice Indent the body of if statements to improve readability. Notice that the Java code corresponds closely to the pseudocode, demonstrating the usefulness of pseudocode as a program-development tool. The body (sometimes called a block) of the if statement contains a statement that displays the string "Passed" in a JLabel. The left brace symbol “{” begins the body of an if statement, and the right brace symbol “}” closes the body of an if statement. The body of an if statement can specify a single action or a sequence of actions (that is, many statements). The braces are required only when the body of an if statement contains more than one statement. We suggest, however, that you always use braces to delimit the body of an if statement. To avoid omitting one or both of the braces, some programmers type the beginning and ending braces of a block even before typing the individual statements in the braces. Notice the indentation of the statement in the body of the if statement. Such indentation makes it easier for you and others to read your application code. The Java compiler ignores white space, such as spaces, tabs and newlines used for indentation and vertical spacing, unless the white space is contained in strings. The condition in the parentheses after keyword if determines whether the statement(s) in the body of the if statement will execute. If the condition is true, the body of the if statement executes. If the condition is false, the body does not execute. Conditions in if statements can be formed by using the equality operators and relational operators, which are summarized in Fig. 6.4. The relational and equality operators all have the same level of precedence. Appendix A contains the complete operator precedence chart. 120 Introducing Algorithms, Pseudocode and Program Control Common Programming Error It is a syntax error to add spaces between the symbols in the operators !=, >= and <= (as in ! =, > =, < =). Common Programming Error Reversal of the symbols in the operators !=, >= and <= (as in =!, =>, =<) is a syntax error. Common Programming Error Using the assignment operator, =, when the equality operator, ==, is intended is a syntax error (unless the the operands are type boolean). Algebraic equality or relational operators Java equality or relational operators Tutorial 6 Example of Java condition Meaning of Java condition Relational operators > > x > y x is greater than y < < x < y x is less than y ≥ >= x >= y x is greater than or equal to y ≤ <= x <= y x is less than or equal to y = == x == y x is equal to y ≠ != x != y x is not equal to y Equality operators Figure 6.4 Equality and relational operators. Figure 6.5 uses a UML activity diagram to illustrate the single-selection if statement. This diagram contains what is perhaps the most important symbol in an activity diagram—the diamond, or decision symbol, which indicates that a decision is to be made. Note the two expressions in square brackets above or next to the arrows leading from the decision symbol—these are called guard conditions. Each transition arrow emerging from a decision symbol has a guard condition. If a particular guard condition is true, the workflow enters the action state to which that transition arrow points. For example, in Fig. 6.5, if the grade is greater than or equal to 60, the application displays “Passed”, then transitions to the final state of this activity. If the grade is less than 60, the application immediately transitions to the final state without displaying a message (because the grade was a failing grade—59 or less). Only one guard condition associated with a particular decision symbol can be true at once. [grade >= 60] display "Passed" [grade < 60] Figure 6.5 if single-selection statement UML activity diagram. Note that the if statement diagrammed in Fig. 6.5, is a single-entry/single-exit statement. The UML activity diagrams for the remaining control statements also contain (aside from small circle symbols and transition arrows) only action-state symbols, indicating actions to be performed, and diamond symbols. Representing control statements in this way emphasizes the action/decision model of programming. To understand the process of structured programming better, you can envision bins, each containing many copies of different types of control statements in the form of UML activity diagrams. The UML activity diagrams in each bin are empty, meaning that nothing is written in the action-state symbols and no guard conditions are written next to the decision symbols. Your task is to assemble an application, using as many appropriate UML activity diagrams as the algorithm demands, combining the control statements in only two possible ways (stacking or nesting) and filling in the actions and decisions (with the decisions’ guard conditions) in a manner appropriate to the algorithm. Again, each particular UML activity diagram is implemented in Java as a control statement. Tutorial 6 Wage Calculator Application SELF-REVIEW 121 1. Which of the following if statements correctly displays that a student received an A on an exam if the score was 90 or above? a) if ( studentGrade != 90 ) { displayJLabel.setText( } b) if ( studentGrade > 90 ) { displayJLabel.setText( } c) if ( studentGrade <= 90 ) { displayJLabel.setText( } d) if ( studentGrade >= 90 ) { displayJLabel.setText( } 2. The symbol a) * c) <> "Student received an A" ); "Student received an A" ); "Student received an A" ); "Student received an A" ); is not a Java operator. b) != d) % Answers: 1) d. 2) c. 6.6 if…else Selection Statement As you have learned, the if selection statement performs an indicated action (or sequence of actions) only when the condition evaluates to true; otherwise, the action (or sequence of actions) is skipped. The if…else selection statement performs an action (or sequence of actions) if a condition is true and performs a different action (or sequence of actions) if the condition is false. For this reason, if…else is known as a double-selection statement. For example, the pseudocode statement If student’s grade is greater than or equal to 60 Display “Passed” else Display “Failed” displays “Passed” if the student’s grade is greater than or equal to 60, but displays “Failed” if the student’s grade is less than 60. In either case, after output occurs, the next pseudocode statement in sequence is “performed.” The preceding pseudocode If…else statement may be written in Java as Good Programming Practice Apply a standard indentation convention consistently throughout your applications to enhance readability. Good Programming Practice Indent both body statements of an if…else statement to improve readability. if ( studentGrade >= 60 ) { displayJLabel.setText( "Passed" ); } else { displayJLabel.setText( "Failed" ); } Note that the body of the else clause is indented so that it lines up with the indented body of the if clause. A standard indentation convention should be applied consistently throughout your applications. It is difficult to read code that does not use uniform spacing conventions. The if…else selection statement follows the same general syntax as the if statement. The else keyword and any related statements are placed following the end of the if statement’s body. Figure 6.6 uses a UML activity diagram to illustrate the flow of control in the if…else double-selection statement. Once again, note that (besides the initial state, transition arrows and final state) the only symbols in the activity diagram rep- 122 Introducing Algorithms, Pseudocode and Program Control Tutorial 6 resent action states and decisions. In this example, the grade is either less than 60 or greater than or equal to 60. If the grade is less than 60, the application displays "Failed". If the grade is greater than or equal to 60, the application displays "Passed". We continue to emphasize this action/decision model of computing. Imagine again a deep bin containing as many empty UML activity diagrams representing double-selection statements as might be needed to build any Java application. Your job as a programmer is to assemble these double-selection statements (by stacking and nesting) with any other control statements required by the algorithm. You fill in the action states and decision symbols with action expressions and guard conditions appropriate to the algorithm. display “Failed” [grade < 60] [grade >= 60] display “Passed” Figure 6.6 if…else double-selection statement UML activity diagram. Good Programming Practice If there are several levels of indentation, each level should be indented further to the right by the same amount of space. Nested if…else statements test for multiple conditions by placing if…else statements inside other if…else statements. For example, the pseudocode in Fig. 6.7 will display “A” for exam grades greater than or equal to 90, “B” for grades in the range 80–89, “C” for grades in the range 70–79, “D” for grades in the range 60–69 and “F” for all other grades. if student’s grade is greater than or equal to 90 Display “A” else If student’s grade is greater than or equal to 80 Display “B” else If student’s grade is greater than or equal to 70 Display “C” else If student’s grade is greater than or equal to 60 Display “D” else Display “F” Figure 6.7 Pseudocode for an application that displays a student’s grades. Common Programming Error Following an else clause with another else or else if clause is a syntax error. The pseudocode in Fig. 6.7 may be written in Java as shown in Fig. 6.8. If studentGrade is greater than or equal to 90, the first condition evaluates to true and the statement displayJLabel.setText( "A" ); is executed. Notice that, with a value for studentGrade greater than or equal to 90, the remaining three conditions would also evaluate to true. These conditions, however, are never evaluated, because they are placed within the else portion of the outer if…else statement. Because the first condition is true, all statements within the else clause are skipped. Now assume studentGrade contains the value 75. The first condition evaluates to false, so the program will execute the statements within the else clause. This else clause also contains an if…else statement, with the condition studentGrade >= 80. This condition evaluates to false, causing the statements in the following else clause to execute. This else clause contains yet another if…else statement, with the condition studentGrade >= 70. This condition is true, causing the statement displayJLabel.setText( "C" ); to execute. The else clause of this if…else statement is then skipped. Tutorial 6 Wage Calculator Application 123 if ( studentGrade >= 90 ) { displayJLabel.setText( "A" ); } else if ( studentGrade >= 80 ) { displayJLabel.setText( "B" ); } else if ( studentGrade >= 70 ) { displayJLabel.setText( "C" ); } else if ( studentGrade >= 60 ) { displayJLabel.setText( "D" ); } else { displayJLabel.setText( "F" ); } Figure 6.8 Java code converted from the pseudocode in Fig. 6.7. Java programmers, when writing nested if…else statements such as the one in Fig. 6.8, often use the format shown in Fig. 6.9. if ( studentGrade >= 90 ) { displayJLabel.setText( } else if ( studentGrade >= { displayJLabel.setText( } else if ( studentGrade >= { displayJLabel.setText( } else if ( studentGrade >= { displayJLabel.setText( } else { displayJLabel.setText( } "A" ); 80 ) "B" ); 70 ) "C" ); 60 ) "D" ); "F" ); Figure 6.9 Nested if…else statements with alternative indentation. The nested if…else statements in Fig. 6.8 and Fig. 6.9 are equivalent, but the latter statement is preferred by some programmers because it avoids deep indentation of the code. Such deep indentation often leaves little room on a line, forcing statements to be split and decreasing code readability. Some programmers feel that the code in Fig. 6.8 better emphasizes the nesting of the if…else statements. SELF-REVIEW 1. if…else is a a) single c) triple -selection statement. b) double d) nested 124 Introducing Algorithms, Pseudocode and Program Control Tutorial 6 2. Placing an if…else statement inside another if…else statement is an example of . a) nesting if…else statements c) creating sequential if…else statements b) stacking if…else statements d) None of the above. Answers: 1) b. 2) a. 6.7 Constructing the Wage Calculator Application Now you will build your Wage Calculator application by using the if…else statement, which will allow you to calculate only regular wages or to include overtime pay based on the number of hours worked. The following pseudocode describes the basic operation of the Wage Calculator application that calculates and displays the employee’s pay when the user clicks the Calculate JButton. When the user clicks the Calculate JButton: Input the hourly wage Input the number of hours worked If the number of hours worked is less than or equal to 40 hours Gross wages equals hours worked times hourly wage else Gross wages equals 40 times hourly wage plus hours above 40 times hourly wage times 1.5 Display gross wages This book teaches programming by using an application-driven approach in which all topics are presented in graphical user interface (GUI) applications. Users interact with GUI applications by clicking JButtons, changing text in JTextFields, pressing keys on the keyboard and the like. Each of these user interactions generates an event in Java on a particular GUI component. For instance, clicking a JButton generates an actionPerformed event for that JButton. This style of programming is referred to as object-oriented, event-driven (OOED) programming—events happen on components (objects) and cause actions. The way you program these applications is by placing your code within methods that handle events. In this way, the desired results of the code occur in response to specific events. Before developing each application, you take it for a test drive. Here you interact with the application’s GUI and begin to understand the purpose of the application. You also learn the GUI components that will be required to obtain user input and display results. Frequently, when determining the requirements of an application, you will design a prototype of the application’s GUI. As you develop each application for the remainder of this textbook, you will use two application development aids— pseudocode and Action/Component/Event (ACE) tables. Pseudocode describes the algorithm—that is, the actions to be performed and the order in which those actions should be performed. As you read the pseudocode, you will see that there are specific actions to perform, such as “Calculate gross wages,” “Input the hourly wage” and “Display gross wages.” An ACE table helps relate the events that occur on GUI components with the actions that should be performed in response to those events. Figure 6.10 presents the Action/Component/Event (ACE) table for the Wage Calculator application. Sometimes, when creating an ACE table, actions in the pseudocode can be lifted and inserted directly in the left column of the table—for instance, “Display gross wages.” In other cases, one action might be represented with a substantial amount of pseudocode—for instance, calculating an employee’s gross wages requires most of the pseudocode that describes the Wage Calculator application. It would be tedious to list all this pseudocode in the table. In such cases, you might use a shorthand representation of the action, such as “Calculate gross wages.” The left column sometimes includes actions that are not represented in the pseudocode at all. For example, the action “Label the application’s components” is Tutorial 6 Wage Calculator Application 125 not part of the pseudocode, but is an important part of constructing this application. The middle column specifies the GUI component or class associated with the action. The right column specifies the event that initiates the action. Action/Component/ Event (ACE) Table for the Wage Calculator Application Action Component Event Label the application’s components hourlyWageJLabel hoursWorkedJLabel grossWagesJLabel Application is run calculateJButton User clicks Calculate Input the hourly wage Input the number of hours worked If the number of hours worked is less than or equal to 40 hours Gross wages equals hours worked times hourly wage else Gross wages equals 40 times hourly wage plus hours above 40 times hourly wage times 1.5 Display gross wages hourlyWageJTextField hoursWorkedJTextField JButton grossWagesJTextField Figure 6.10 ACE table for the Wage Calculator application. The JLabels in the first row of Fig. 6.10 label the application’s components for the user. The setText method will be used with each JLabel to specify the text displayed on the JLabel. In the second row, the user clicks calculateJButton to calculate the gross wages for an employee. In the third column of this row, the phrase “User clicks Calculate JButton” indicates the event that initiates the calculation. The JTextFields in the third and fourth rows will obtain input from the user. For each JTextField, the getText method will be used to obtain the input from the JTextField. The second to last row shows the if…else statement that determines the gross wages. The setText method of the component in the last row, grossWagesJTextField, displays the gross wages. You will now use the pseudocode and the ACE table to complete your own version of this application. The following box will guide you through the process of declaring the variables you’ll need to calculate the employee’s wages in the Calculate JButton’s event handler (calculateJButtonActionPerformed). You will use the variables to store input from the user. Then, you will use those variables in an if…else statement to compute the employee’s gross wages. Finally, you will display the gross wages. If you forget to add code for this actionPerformed event, the application will not respond when the user clicks the Calculate JButton. Implementing the Calculate JButton’s actionPerformed Event Handler 1. Copying the template to your working directory. Copy the C:\Examples\ Tutorial06\TemplateApplication\WageCalculator directory to your C:\SimplyJava directory. 2. Opening the Wage Calculator application’s template file. Open the template file WageCalculator.java in your text editor. 3. Locating the calculateJButtonActionPerformed event handler. In this example, the event handler calculates the gross wages when the user clicks the Calculate JButton. Lines 109–112 of Fig. 6.11 show the initially empty event handler. Next, you will write the code for this event handler so that your application will indeed calculate and display the gross wages. 126 Introducing Algorithms, Pseudocode and Program Control Tutorial 6 (cont.) Calculate JButton event handler Figure 6.11 calculateJButtonActionPerformed event handler (initially empty). Notice the comments on lines 108 and 112. In lines 110 and 112, the “{” and “}” symbols indicate the body of the event handler calculateJButtonActionPerformed. The comment after the “}” symbol documents the end of the event handler. 4. Declaring variables and obtaining inputs from the JTextFields. This application uses primitive type double. As you learned in Tutorial 5, type double is used to represent floating-point numbers (that is, numbers with decimal points). Because an employee’s hourly wage and hours worked are often fractional numbers, the data type int is not appropriate for this application. Insert lines 111–117 of Fig. 6.12 into calculateJButtonActionPerformed. The statement in lines 112–113 declares double variable hourlyWage and assigns to it the double value of the hourlyWageJTextField’s text property. The statement in lines 116–117 declares double variable hoursWorked and assigns to it the double value of the hoursWorkedJTextField’s text property. Notice that lines 113 and 117 both use the Double.parseDouble method to convert a String to a double value. Declare variable hourlyWage and assign it the user input from hourlyWageJTextField Declare variable hoursWorked and assign it the user input from hoursWorkedJTextField Figure 6.12 Assigning user input to variables. 5. Good Programming Practice Capitalize all letters in a constant’s name to make the constant stand out in the application. Separate each word in the name of a constant with an underscore to make the identifier easier to read. Declaring a constant. Add lines 119–121 of Fig. 6.13 in the event handler calculateJButtonActionPerformed. Line 121 contains a constant—a variable whose value cannot be changed after its initial declaration. Constants are declared by preceding the data type with the keyword final. In this case, you assign to the constant HOUR_LIMIT the maximum number of hours worked before mandatory overtime pay (40.0). Notice that you capitalize the constant’s name to emphasize that it is a constant. Constant declaration Figure 6.13 Creating a constant. Tutorial 6 Wage Calculator Application (cont.) 6. 127 Declaring a variable to store the gross wages. Add lines 123–124 of Fig. 6.14 to calculateJButtonActionPerformed. Line 124 contains a variable declaration for the variable wages, which you will use to store the employee’s gross wages for the week. Declare double variable wages Figure 6.14 Declaring a variable of type double. 7. Determining wages based on hours worked. Add lines 126–140 of Fig. 6.15 in the event handler calculateJButtonActionPerformed. This if…else statement determines whether the employee worked overtime and calculates the gross wages accordingly. if…else statement to calculate wages Figure 6.15 if…else statement that calculates gross wages. Line 127 determines whether the value stored in hoursWorked is less than or equal to HOUR_LIMIT (40.0, specified in line 121). If it is, then line 130 calculates the product of hoursWorked and hourlyWage and assigns the result to wages. If, on the other hand, hoursWorked is greater than HOUR_LIMIT, then execution proceeds to the else clause in lines 132–140. Line 135 computes the wages for the hours worked up to the limit set by HOUR_LIMIT (that is, 40.0) and assigns the result to wages. Lines 138–139 calculate the user’s overtime pay and add it to the wages calculated in line 135. The expression in line 139 first determines the user’s overtime hours (by using the calculation hoursWorked - HOUR_LIMIT), then multiplies the overtime hours by the product of 1.5 times the user’s hourly wage. The overtime pay is then added to the value of wages, and the result is assigned to wages. 8. Displaying the result. Insert lines 142–143 of Fig. 6.16 in calculateJButtonActionPerformed. Line 143 converts the value in the variable wages to a String and uses that String to set the text property of the grossWagesJTextField. 9. Saving the application. Save your modified source code file. 128 Introducing Algorithms, Pseudocode and Program Control Tutorial 6 (cont.) Displaying output Figure 6.16 Displaying gross wages in the grossWagesJTextField. 10. Opening the Command Prompt window and changing directories. Open the Command Prompt window by selecting Start > Programs > Accessories > Command Prompt. Change to your working directory by typing cd C:\SimplyJava\WageCalculator. 11. Compiling the application. Compile your application by typing javac WageCalculator.java. 12. Running the application. When your application compiles correctly, run it by typing java WageCalculator. Figure 6.17 shows the updated applica- tion running. Notice that the output in Fig. 6.17 is not yet formatted as a proper dollar amount as it should be in the completed application. You will learn how to properly format the dollar amount in Section 6.9. Displaying unformatted number Figure 6.17 Updated application displaying unformatted number. 13. Closing the application. Close your running application by clicking its close button. 14. Closing the Command Prompt window. Close the Command Prompt window by clicking its close button. SELF-REVIEW 1. The double type can be used to store a) letters and digits c) strings 2. Constants are declared with the keyword a) fixed c) final . b) numbers with decimal points d) None of the above. . b) constant d) const Answers: 1) b. 2) c. 6.8 Assignment Operators Java provides several assignment operators for abbreviating assignment statements. For example, the statement value = value + 3; which adds 3 to the value in the variable value, can be abbreviated with the addition assignment operator += as value += 3; Tutorial 6 Wage Calculator Application 129 The addition assignment (+=) operator adds the value of its right operand to the current value of its left operand and stores the result in the left operand. Java provides assignment operators for several binary operators, including +, -, *, / and %. When an addition assignment statement is evaluated, the expression to the right of the operator is always evaluated first, then added to the variable on the left. Figure 6.18 includes the arithmetic assignment operators, sample expressions using these operators and explanations. Sample expression Explanation Assigns to c += c += 7 c=c+7 11 -= c -= 3 c=c-3 1 *= c *= 4 c=c*4 16 /= c /= 2 c=c/2 2 %= c %= 3 c=c%3 1 Assignment operators Assume c = 4 Figure 6.18 Arithmetic assignment operators. Next, you will learn how to abbreviate your overtime wages calculation with the += operator. When you run the application again, you will notice that the application runs the same as before. Using the Addition Assignment Operator 1. Opening the Wage Calculator application’s template file. Open the template file WageCalculator.java in your text editor. 2. Using the addition assignment operator. Replace lines 138–139 of Fig. 6.15 with lines 138–139 of Fig. 6.19. The new statement uses the addition assignment operator, making it unnecessary to include the wages variable in both the left and right operands of the assignment. The statement still performs the same action—the overtime pay for the employee is calculated and added to the regular wages earned. Addition assignment operator Figure 6.19 Using the addition assignment operator in a calculation. 3. Saving the application. Save your modified source code file. 4. Opening the Command Prompt window and changing directories. Open the Command Prompt window by selecting Start > Programs > Accessories > Command Prompt. Change to your working directory by typing cd C:\SimplyJava\WageCalculator. 5. Compiling the application. Compile your application by typing javac WageCalculator.java. 6. Running the application. When your application compiles correctly, run it by typing java WageCalculator. Notice that the application executes as it did in the previous box. Once you have finished testing the application, close it. 7. Closing the application. Close your running application by clicking its close button. 130 Introducing Algorithms, Pseudocode and Program Control SELF-REVIEW 1. The *= operator Tutorial 6 . a) adds the value of its right operand to the value of its left operand and stores the result in its left operand b) creates a new variable and assigns the value of the right operand to that variable c) multiplies the value of its left operand by the value of its right operand and stores the result in its left operand d) None of the above. 2. If the variable x contains the value 5, what value will x contain after the expression x -= 3 is executed? a) 3 c) 7 b) 5 d) 2 Answers: 1) c. 2) d. 6.9 Formatting Text There are several ways to format output in Java. In this section, you will use class DecimalFormat’s method format to control how text displays. Modifying the appearance of text for display purposes is known as text formatting. DecimalFormat is a class that is used to format decimal numbers. Method format of DecimalFormat takes a double argument and returns a String that contains formatted double values. Recall that your Wage Calculator application does not display the result of its calculation with the appropriate decimal places and dollar sign that you saw when test-driving the application. Next, you will learn how to apply currency formatting to the value in the Gross wages: JTextField. Formatting the Gross Wages 1. Opening the Wage Calculator application’s template file. Open the template file WageCalculator.java in your text editor. 2. Modifying the Calculate JButton’s actionPerformed event. Replace lines 142–143 of Fig. 6.16 with lines 142–146 of Fig. 6.20. Line 143 creates the DecimalFormat variable dollars, which is initialized with the pattern "$0.00". Each 0 specifies a required digit position in the formatted floating-point number. This particular format indicates that every number formatted with dollars will have a dollar sign followed by at least one digit to the left of the decimal point and exactly two digits to the right of the decimal point. In line 146, the expression dollars.format( wages ) formats the value of variable wages. The resulting String is used as the value of grossWagesJTextField’s text property. The formatted number is rounded to the nearest hundredth. DecimalFormat for dollar values Displays wages in dollar format Figure 6.20 Using the format method of DecimalFormat to display the gross wages as currency. 3. Saving the application. Save your modified source code file. Tutorial 6 Wage Calculator Application (cont.) 4. 5. 6. 131 Opening a Command Prompt window and changing directories. Open the Command Prompt window by selecting Start > Programs > Accessories > Command Prompt. Change to your working directory by typing cd C:\SimplyJava\WageCalculator. Compiling the application. Compile your application by typing javac WageCalculator.java. Running the application. When your application compiles correctly, run it by typing java WageCalculator. Figure 6.21 shows the completed application running with a properly formatted number. Displaying formatted number Figure 6.21 Completed application displaying formatted wages. 7. 8. Good Programming Practice Place a blank line above and below each if…else statement to help make your applications more readable. In general, do this for all control statements. Closing the application. Close your running application by clicking its close button. Closing the Command Prompt window. Close the Command Prompt window by clicking its close button. Figure 6.22 shows the completed source code of the Wage Calculator application. The lines of code that you added, viewed or modified in this tutorial are highlighted. In lines 125–141, notice the use of blank lines above and below the if…else statement. Such vertical spacing makes your applications easier to read. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // Tutorial 6: WageCalculator.java // This application inputs the hourly wage and number of hours // worked for an employee, then calculates the employee's gross // wages (with overtime for hours worked over 40 hours). import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.text.*; public class WageCalculator extends JFrame { // JLabel and JTextField for wage per hour private JLabel hourlyWageJLabel; private JTextField hourlyWageJTextField; // JLabel and JTextField for hours worked in a week private JLabel hoursWorkedJLabel; private JTextField hoursWorkedJTextField; // JLabel and JTextField for gross wages private JLabel grossWagesJLabel; private JTextField grossWagesJTextField; // JButton to initiate wage calculation private JButton calculateJButton; Figure 6.22 Wage Calculator application completed source code. (Part 1 of 4.) 132 Introducing Algorithms, Pseudocode and Program Control 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 Tutorial 6 // no-argument constructor public WageCalculator() { createUserInterface(); } // create and position GUI components; register event handlers public void createUserInterface() { // get content pane for attaching GUI components Container contentPane = getContentPane(); // enable explicit positioning of GUI components contentPane.setLayout( null ); // set up hourlyWageJLabel hourlyWageJLabel = new JLabel(); hourlyWageJLabel.setBounds( 16, 16, 90, 21 ); hourlyWageJLabel.setText( "Hourly wage:" ); contentPane.add( hourlyWageJLabel ); // set up hourlyWageJTextField hourlyWageJTextField = new JTextField(); hourlyWageJTextField.setBounds( 120, 16, 90, 21 ); hourlyWageJTextField.setHorizontalAlignment( JTextField.RIGHT ); contentPane.add( hourlyWageJTextField ); // set up hoursWorkedJLabel hoursWorkedJLabel = new JLabel(); hoursWorkedJLabel.setBounds( 16, 56, 90, 21 ); hoursWorkedJLabel.setText( "Hours worked:" ); contentPane.add( hoursWorkedJLabel ); // set up hoursWorkedJTextField hoursWorkedJTextField = new JTextField(); hoursWorkedJTextField.setBounds( 120, 56, 90, 21 ); hoursWorkedJTextField.setHorizontalAlignment( JTextField.RIGHT ); contentPane.add( hoursWorkedJTextField ); // set up grossWagesJLabel grossWagesJLabel = new JLabel(); grossWagesJLabel.setBounds( 16, 96, 90, 21 ); grossWagesJLabel.setText( "Gross wages:" ); contentPane.add( grossWagesJLabel ); // set up grossWagesJTextField grossWagesJTextField = new JTextField(); grossWagesJTextField.setBounds( 120, 96, 90, 21 ); grossWagesJTextField.setHorizontalAlignment( JTextField.RIGHT ); grossWagesJTextField.setEditable( false ); contentPane.add( grossWagesJTextField ); // set up calculateJButton calculateJButton = new JButton(); Figure 6.22 Wage Calculator application completed source code. (Part 2 of 4.) Tutorial 6 Convert hourly wage to double by using Double.parseDouble Convert hours worked to double by using Double.parseDouble Keyword final specifies that HOUR_LIMIT is a constant Variable to store gross wages Begin if…else statement End if part of if…else statement and begin else part; else body executes when condition in line 127 evalues to false Assign to left operand the result of adding left and right operands End else part of if…else Wage Calculator Application 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 133 calculateJButton.setBounds( 120, 136, 90, 24 ); calculateJButton.setText( "Calculate" ); contentPane.add( calculateJButton ); calculateJButton.addActionListener( new ActionListener() // anonymous inner class { // event handler called when calculateJButton is pressed public void actionPerformed ( ActionEvent event ) { calculateJButtonActionPerformed( event ); } } // end anonymous inner class ); // end call to addActionListener // set properties of application’s window setTitle( "Wage Calculator" ); // set title bar text setSize( 230, 200 ); // set window size setVisible( true ); // display window } // end method createUserInterface // method called when user presses calculateJButton private void calculateJButtonActionPerformed( ActionEvent event ) { // get hourly wage double hourlyWage = Double.parseDouble( hourlyWageJTextField.getText() ); // get number of hours worked this week double hoursWorked = Double.parseDouble( hoursWorkedJTextField.getText() ); // constant for maximum hours employee can // work before being paid for overtime final double HOUR_LIMIT = 40.0; // gross wages for week; calculated in if...else statement double wages; // determine gross wages if ( hoursWorked <= HOUR_LIMIT ) { // regular wages for HOUR_LIMIT (40) hours or less wages = ( hoursWorked * hourlyWage ); } else // worked more than HOUR_LIMIT (40) hours { // wages for first HOUR_LIMIT (40) hours wages = HOUR_LIMIT * hourlyWage; // add time-and-a-half for overtime hours wages += ( hoursWorked - HOUR_LIMIT ) * ( 1.5 * hourlyWage ); } Figure 6.22 Wage Calculator application completed source code. (Part 3 of 4.) 134 Introducing Algorithms, Pseudocode and Program Control Format result as a dollar amount Tutorial 6 // specify output format 142 DecimalFormat dollars = new DecimalFormat( "$0.00" ); 143 144 // display gross wages 145 grossWagesJTextField.setText( dollars.format( wages ) ); 146 147 148 } // end method calculateJButtonActionPerformed 149 150 // main method 151 public static void main( String args ) 152 { 153 WageCalculator application = new WageCalculator(); 154 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 155 156 } // end method main 157 158 } // end class WageCalculator Figure 6.22 Wage Calculator application completed source code. (Part 4 of 4.) SELF-REVIEW 1. Class DecimalFormat is used to a) create constant variables c) control how decimal numbers are formatted as text . b) format Java statements d) All of the above. 2. Method of DecimalFormat can display double values in a special format, such as with two digits to the right of the decimal point. a) format c) formatDouble b) getFormat d) setHundred Answers: 1) c. 2) a. 6.10 Using the Debugger: The print and set Commands Java includes several debugging commands that are accessible from the commandline debugger. As you learned in Section 5.6, the print command allows you to examine the value of a variable. In this section, you will learn how to use the print command to examine the value of more complex expressions. The set command allows the programmer to assign new values to variables. Using the Debugger: The print and set commands 1. Opening the Command Prompt window and changing directories. Open the Command Prompt window by selecting Start > Programs > Accessories > Command Prompt. Change to your working directory by typing cd C:\SimplyJava\WageCalculator. 2. Compiling the application for debugging. Compile the application with the -g command-line option by typing javac -g WageCalculator.java. As you learned in Section 5.6, the Java debugger works only with .class files compiled with the -g compiler option. 3. Starting debugging. In the Command Prompt, type jdb. This command will start the Java debugger. 4. Inserting breakpoints. Set a breakpoint at line 116 in the source code by typing stop at WageCalculator:116 (Fig. 6.23). Set another breakpoint at line 130 of the code by typing stop at WageCalculator:130. Tutorial 6 Wage Calculator Application 135 (cont.) Figure 6.23 Setting breakpoints at lines 116 and 130. 5. Running the application. Type run WageCalculator to begin the debugging process. Type 12 in the Hourly wage: JTextField and type 40 in the Hours worked: JTextField (Fig. 6.24). Figure 6.24 Suspended application execution. 6. Suspending application execution. Click the Calculate JButton. This will cause event handler calculateJButtonActionPerformed to execute until the breakpoint at line 116 is reached. This suspends application execution and switches the application into break mode (Fig. 6.25). At this point, the statement in lines 112–113 (Fig. 6.22) has assigned the hourly wage input by the user (12) to variable hourlyWage, and the statement in lines 116–117 is the next statement that will be executed. Figure 6.25 Application execution suspended when debugger reaches the breakpoint at line 116. 136 Introducing Algorithms, Pseudocode and Program Control (cont.) 7. Tutorial 6 Examining data. Once the application has entered break mode, you can explore the values of your variables using the debugger’s print command. In the Command Prompt window, type print hourlyWage. The value will be displayed (Fig. 6.26). Notice that this value is 12.0—the value assigned to hourlyWage in line 112. Value of variable hourlyWage Figure 6.26 Examining variable hourlyWage. 8. Evaluating arithmetic and boolean expressions. In the Command Prompt window, type print (hourlyWage + 3) * 5. Notice that the print command can evaluate arithmetic expressions. In this case, it returns the value 75.0 (Fig. 6.27). In the Command Prompt window, type print hourlyWage == 3. Expressions containing the == symbol are treated as boolean expressions. The value returned is false (Fig. 6.27), because hourlyWage does not currently contain the value 3. Evaluating an arithmetic expression Evaluating a boolean expression Figure 6.27 Examining the values of expressions. 9. Resuming execution. Type cont to resume execution (Fig. 6.28). The application will continue to execute until the next breakpoint, at line 130. Lines 116–117 (Fig. 6.22) execute, assigning the hours worked value (40) to hoursWorked. Line 121 declares constant HOUR_LIMIT and assigns it an initial value (40.0). Line 124 declares variable wages to store the gross wages. The if condition in line 127 evaluates to true, so the if statement’s body executes and the application is once again suspended at line 130. Type print hoursWorked (Fig. 6.28). The hoursWorked value will be displayed. Resume execution Display value of variable hoursWorked Figure 6.28 Resuming execution and displaying the value of the variable hoursWorked. 10. Modifying values. Based on the values input by the user (12 and 40), the gross wages output by the Wage Calculator application should be $480.00. However, by using the debugger, you can change the values of variables in the middle of the application’s execution. This can be valuable for experimenting with different values and for locating logic errors in applications. You can use the debugger’s set command to change the value of a variable. Type set hoursWorked = 10.0. The debugger changes the value of hoursWorked and displays its new value (Fig. 6.29). Tutorial 6 Wage Calculator Application 137 (cont.) Value modified in the debugger Figure 6.29 Modifying values. 11. Viewing the application result. Type cont to continue application execution. Method calculateJButtonActionPerformed finishes execution and displays the result in the Gross wages: JTextField. Notice that the result is $120.00 (Fig. 6.30). This shows that the previous step changed the value of hoursWorked from the user input value (40) to 10.0. The Hours worked: JTextField still displays the value 40, because you changed the value of hoursWorked, but not the text property of the Hours worked: JTextField. Once the event handler finishes executing, the final results are displayed in the Wage Calculator window. Gross wages result based on altered value of variable hoursWorked Figure 6.30 Output displayed after the debugging process. 12. Closing the application. Close your running application by clicking its close button. 13. Closing the Command Prompt window. Close the Command Prompt window by clicking its close button. SELF-REVIEW 1. You can examine the value of an expression by using the debugger’s mand. a) run c) print b) set d) stop 2. You can modify the value of a variable by using the debugger’s a) run c) print com- command. b) set d) stop Answers: 1) c. 2) b. 6.11 Wrap-Up In this tutorial, you learned techniques for solving programming problems. You were introduced to algorithms, pseudocode, the UML and control statements. You learned different types of control statements and when each might be used. You began by test-driving an application that used an if…else statement to determine an employee’s gross wages. You learned the if and if…else control statements and studied UML activity diagrams that showed the decision-making processes of these statements. 138 Introducing Algorithms, Pseudocode and Program Control Tutorial 6 You learned how to format text by using the DecimalFormat method format and how to abbreviate mathematical statements by using the arithmetic assignment operators. In the Using the Debugger section, you learned how to use the print command to examine the value of an expression and how to use the set command to change the value of a variable. In the next tutorial, you will learn how to use message dialogs to display information to the user. You will study the logical operators, which give you more expressive power for forming the conditions in your control statements. You will use the JCheckBox component to allow the user to select from various options in an application. SKILLS SUMMARY Choosing Among Alternate Courses of Action s Use the if, if…else or nested if…else control statements. Conceptualizing the Application Before Using Java s Use pseudocode. s Create an Action/Component/Event (ACE) table. Understanding the Flow of Control in Control Statements s View the control statement’s corresponding UML activity diagram. Performing Comparisons in Conditions s Use the equality (== and !=) and relational (<, <=, > and >=) operators. Creating a Constant s Use the final keyword at the beginning of the variable’s declaration. s Assign a value to the constant in the declaration. Abbreviating Assignment Expressions s Use the assignment operators +=, -=, *=, /= and %=. Formatting a Decimal Value s Use method format of class DecimalFormat to format decimal numbers. Examining Expression Values During Application Execution s Use the debugger to set a breakpoint, and examine expressions using the print command. Modifying Data During Application Execution s KEY TERMS Use the debugger to set a breakpoint, and modify variable values using the set command. ACE table—A program development tool you can use to relate GUI events with the actions that should be performed in response to those events. action/decision model of programming—Representing control statements as UML activity diagrams with action-state symbols, indicating actions to be performed, and diamond symbols, indicating decisions to be made. action expression (in the UML)—Used in an action state within a UML activity diagram to specify a particular action to perform. action state (in the UML)—An action (represented by an action-state symbol) to perform in a UML activity diagram. action-state symbol (in the UML)—A rectangle with its left and right sides replaced with arcs curving outward that represents an action to perform in a UML activity diagram. activity diagram (in the UML)—A UML diagram that models the activity (also called the workflow) of a portion of a software system. algorithm—A procedure for solving a problem, specifying the actions to be executed and the order in which these actions are to be executed. block—A set of statements that is enclosed in curly braces ({ and }). boolean type—A type that represents the values true and false. Tutorial 6 Wage Calculator Application 139 condition— A boolean expression with a true or false value that is used to make a decision. constant—A variable whose value cannot be changed after its initial declaration. control statement—A program statement (such as if, if…else, switch, while, do…while or for) that specifies the flow of control (that is, the order in which statements execute). control-statement nesting—Placing one control statement in the body of another control statement. control-statement stacking—A set of control statements in sequence. The exit point of one control statement is connected to the entry point of the next control statement in sequence. DecimalFormat—The class used to format floating-point numbers (that is, numbers with decimal points). decision symbol (in the UML)—The diamond-shaped symbol in a UML activity diagram that indicates a decision is to be made. diamond (in the UML)—The symbol (also known as the decision symbol) in a UML activity diagram that indicates a decision is to be made. [Note: In a later tutorial, you will learn that this symbol serves two purposes in the UML.] dotted line (in the UML)—A UML activity diagram symbol that connects each UML-style note with the element that the note describes. Double.parseDouble method—A method that converts a String containing a floating-point number into a double value. double type—A type that can represent numbers with decimal points. double-selection statement—A statement, such as if…else, that selects between two different actions or sequences of actions. equality operators—Operators == (is equal to) and != (is not equal to) that compare two values. executable statement—An action that is performed when the corresponding Java application is run. false—One of the two possible values for a boolean type; the other is true. final keyword—Precedes the data type in a declaration of a constant. final state (in the UML)—A solid circle surrounded by a hollow circle (a “bullseye”) in a UML activity diagram. It represents the end of the workflow after an application performs its activities. format method of DecimalFormat—Method that returns a String containing a formatted number. formatting—Modifying the appearance of text for display purposes. guard condition (in the UML)—A condition contained in square brackets that must be associated with a transition arrow leading from a decision symbol in a UML activity diagram. The guard condition associated with a particular transition determines whether workflow continues along that path. if statement—The if single-selection statement performs an action (or sequence of actions) based on a condition. if…else statement—The if…else double-selection statement performs an action (or sequence of actions) if a condition is true and performs a different action (or sequence of actions) if the condition is false. initial state (in the UML)—The beginning of the workflow in a UML activity diagram before the application performs the activities. multiple-selection statement—A statement that selects from among many different actions or sequences of actions, such as the switch statement. nested statement—A statement that is placed inside another control statement. note (in the UML)—An explanatory remark (represented by a rectangle with a folded upperright corner) describing the purpose of a symbol in a UML activity diagram. object-oriented, event-driven programming (OOED)—Using objects, such as GUI components, to enable users to interact with an application. Each interaction generates an event, which causes the application to perform an action. print command (in the debugger)—A debugger command that is used to examine the values of variables and expressions. 140 Introducing Algorithms, Pseudocode and Program Control Tutorial 6 program control—The task of executing an application’s statements in the correct order. pseudocode—An informal language that helps programmers develop algorithms. relational operators—Operators < (less than), > (greater than), <= (less than or equal to) and >= (greater than or eqaul to) that compare two values. repetition statement—A control statement that might cause an application to execute statements multiple times. selection statement—A control statement that selects among alternative courses of action. set command (in the debugger)—A debugger command that is used to change the value of a variable. single-entry/single-exit control statement—Each control statement has one entry point and one exit point. single-selection statement—A statement, such as the if statement, that selects or ignores a single action or sequence of actions. small circles (in the UML)—The solid circle in an activity diagram represents the activity’s initial state and the solid circle surrounded by a hollow circle represents the activity’s final state. solid circle (in the UML)—A UML activity diagram symbol that represents the activity’s initial state. structured programming—A technique for organizing program control to help you develop applications that are easy to understand, debug and modify. transition (in the UML)—A change from one action state to another that is represented by transition arrows in a UML activity diagram. true—One of the two possible values for a boolean type; the other is false. UML (Unified Modeling Language)—An industry standard for modeling software systems graphically. workflow—The activity of a portion of a software system. JAVA LIBRARY REFERENCE DecimalFormat Class DecimalFormat is used to format floating-point numbers (that is, numbers with decimal points). s Methods format—Converts a double value into a specified format. MULTIPLE-CHOICE QUESTIONS 6.1 The and. operator returns false if the left operand is greater than the right oper- a) == c) <= b) < d) All of the above. 6.2 A occurs when an executed statement does not directly follow the previously executed statement in the written application. a) transition c) logical error b) flow d) transfer of control 6.3 A variable or an expression can be examined by the a) print c) display 6.4 The if statement is called a action (or sequence of actions). a) single-selection c) double-selection statement because it selects or ignores one b) multiple-selection d) repetition 6.5 The three types of program control are sequence, selection and a) reduction c) branching debugger command. b) get d) examine b) decision d) repetition . Tutorial 6 141 Wage Calculator Application 6.6 In an activity diagram, a rectangle with curved sides represents a) a complete algorithm c) an action . b) a comment d) the termination of the application 6.7 The body of an if statement that contains multiple statements is placed in a) () c) <> . b) d) {} 6.8 A variable of type boolean can be assigned the values a) true, false c) one, zero and . b) off, on d) yes, no 6.9 A variable whose value cannot be changed after its initial declaration is called a . a) double c) standard 6.10 The right operands. b) constant d) boolean operator assigns to the left operand the result of adding the left and a) + c) += EXERCISES b) =+ d) + = 6.11 (Currency Converter Application) Develop an application that functions as a currency converter as shown in Fig. 6.31. The user provides a number in the Dollars to convert: JTextField and a currency name (as text) in the Convert from dollars to: JTextField. Clicking the Convert JButton will convert the specified amount into the indicated currency and display it in a JLabel. Your application should be able to convert currency amounts from dollars to euros, yen and pesos, using the following exchange rates: 1 Dollar = 1.02 Euros, 120 Yen and 10 Pesos. [Note: Currency exchange rates are constantly changing. There are many online sites where you can view current exchange rates, including finance.yahoo.com/m3, www.x-rates.com and www.rubicon.com/passport/currency/currency.html.] Figure 6.31 Currency Converter GUI. a) Copying the template to your working directory. Copy the directory C:\Examples\ Tutorial06\Exercises\CurrencyConverter to your C:\SimplyJava directory. b) Opening the template file. Open the CurrencyConverter.java file in your text editor. c) Obtaining the user input. In the convertJButtonActionPerformed event handler (lines 105–108), insert a statement that uses method Double.parseDouble to convert the user input from the dollarJTextField to a double and assigns the result to double variable amount. d) Obtaining the currency name. Add a statement that obtains the currency name from the typeJTextField and assigns it to String variable currencyName. e) Performing the currency conversion. Next, you will use a nested if…else statement to determine which currency the user entered, then perform the appropriate conversion. To compare currencyName with another String, you will use String method equals—as in the expression currencyName.equals( "Euros" ). String method equals performs a case sensitive comparison and returns true if the String to the left of the dot (.) is identical to the String in parentheses; otherwise, the method 142 Introducing Algorithms, Pseudocode and Program Control Tutorial 6 returns false. Insert a nested if…else statement with three conditions. In the first condition, use the expression currencyName.equals( "Euros" ), which evaluates to true if currencyName contains "Euros"—the spelling, including uppercase and lowercase letters, must be indentical. If this condition is true, the body of this if statement should convert the dollars to euros by multiplying amount by 1.02 and storing the result in amount. Otherwise, in the nested if statement, test the condition currencyName.equals( "Yen" ). If this condition is true, the body of this if statement will convert the dollars to yen by multiplying amount by 120 and storing the result in amount. Finally, if the first two conditions are false, the third nested if statement should test the condition currencyName.equals( "Pesos" ). If this condition is true, the body of this if statement should convert the dollars to pesos by multiplying the amount by 10 and storing the result in amount. f) Displaying the result. Insert a statement that creates a DecimalFormat as you did in the Wage Calculator application (Fig. 6.20, line 143), but without the “$” sign. Finally, display the formatted result in convertedJTextField. g) Opening the Command Prompt window and changing directories. Open the Command Prompt window by selecting Start > Programs > Accessories > Command Prompt. Change to your working directory by typing cd C:\SimplyJava\CurrencyConverter. h) Saving the application. Save your modified source code file. i) Compiling the application. Compile your application by typing javac CurrencyConverter.java. j) Running the completed application. When your application compiles correctly, run it by typing java CurrencyConverter. Type 20.00 in the Dollars to convert: JTextField and type Yen in the Convert from dollars to: JTextField, then press the Convert JButton. Ensure that the converted value 2400.00 appears in the Converted amount: JTextField. Type Euros in the Convert from dollars to: JTextField, then press the Convert JButton. Ensure that the converted value 20.40 appears in the Converted amount: JTextField. Type Pesos in the Convert from dollars to: JTextField, then press the Convert JButton. Ensure that the converted value 200.00 appears in the Converted amount: JTextField. Finally, type anything else in the Convert from dollars to: JTextField, then press the Convert JButton. Notice that the application simply displays the dollar amount if an incorrect type is entered. k) Closing the application. Close your running application by clicking its close button. l) Closing the Command Prompt window. Close the Command Prompt window by clicking its close button. 6.12 (Expanded Wage Calculator that Performs Tax Calculations) Develop an application that calculates an employee’s wages as shown in Fig. 6.32. The user enters the hourly wage and number of hours worked per week. When the Calculate JButton is clicked, the gross wages of the user should display in the Gross wages: JTextField. The Federal taxes: JTextField should display the amount deducted for Federal taxes, and the Net wages: JTextField should display the difference between the gross wages and the Federal tax amount. Assume overtime wages are 1.5 times the hourly wage and Federal withholding taxes are 15% of gross earnings. a) Copying the template to your working directory. Copy the directory C:\Examples\ Tutorial06\Exercises\ExpandedWageCalculator to your C:\SimplyJava directory. b) Opening the template file. Open the WageCalculator.java file in your text editor. c) Modifying the Calculate JButton’s ActionPerformed event handler. Add the code for Steps d and e to calculateJButtonActionPerformed (lines 192–231). Tutorial 6 Wage Calculator Application 143 Figure 6.32 Expanded Wage Calculator GUI. d) Calculating and displaying the Federal taxes deducted.After line 230, insert a statement that declares a constant double variable—TAX_RATE—and assigns it 0.15, which represents 15%. On the next line, insert a statement that declares double variable federalTaxes and assigns it the product of wages and TAX_RATE. The result is the amount that will be deducted for Federal taxes from the gross wages. Insert a statement that displays this value in federalTaxesJTextField, using method format of DecimalFormat dollars that you created earlier (see Fig. 6.20 for the basic syntax of this statement). e) Calculating and displaying the employee’s net wages. Insert a statement that subtracts federalTaxes from wages to calculate the employee’s net wages. Display this value in netWagesJTextField, using method format of DecimalFormat dollars. f) Opening the Command Prompt window and changing directories. Open the Command Prompt window by selecting Start > Programs > Accessories > Command Prompt. Change to your working directory by typing cd C:\SimplyJava\ExpandedWageCalculator. g) Saving the application. Save your modified source code file. h) Compiling the application. Compile your application by typing javac WageCalculator.java. i) Running the completed application.When your application compiles correctly, run it by typing java WageCalculator. Type 10 in the Hourly wage: JTextField and type 45 in the Hours worked: JTextField, then press the Calculate JButton. Ensure that the results appear as shown in Fig. 6.32. j) Closing the application. Close your running application by clicking its close button. k) Closing the Command Prompt window. Close the Command Prompt window by clicking its close button. 6.13 (Credit Checker Application) Develop an application (as shown in Fig. 6.33) that a credit manager can use to determine whether a department store customer has exceeded the credit limit on a charge account. For each customer, the credit manager enters an account number (an int), a balance at the beginning of the month (a double), the total of all items charged this month (a double), the total of all credits applied to the customer’s account this month (a double) and the customer’s allowed credit limit (a double). The application should input each of these facts, calculate the new balance (= beginning balance + charges – credits), display the new balance and determine whether the new balance exceeds the customer’s credit limit. If the customer’s credit limit is exceeded, the application should display a message (in an output JTextField at the bottom of the JFrame) informing the of this fact. a) Copying the template to your working directory. Copy the directory C:\Examples\ Tutorial06\Exercises\CreditChecker to your C:\SimplyJava directory. b) Opening the template file. Open the CreditChecker.java file in your text editor. c) Coding the Calculate Balance JButton’s ActionPerformed event handler. Add the code for Steps d through f to event handler calculateJButtonActionPerformed (lines 196–199). 144 Introducing Algorithms, Pseudocode and Program Control Tutorial 6 Figure 6.33 Credit Checker GUI. d) Declaring variables. Starting in line 198, insert statements that declare four double variables—startBalance, totalCharges, totalCredits and creditLimit. Assign to each of these variables the value from the corresponding JTextField (startBalanceJTextField, totalChargesJTextField, totalCreditsJTextField and creditLimitJTextField, respectively) converted to type double. e) Calculating and displaying the new balance. Declare a fifth double variable called newBalance to store the new balance in the account after the charges and credits have been applied. Calculate the new balance by adding the total charges to the starting balance and subtracting the credits. Assign the result to newBalance. Declare a DecimalFormat dollarFormat, as you did in Fig. 6.20. Format the newBalance using dollarFormat and display the formatted number in newBalanceJtextField. f) Determining if the credit limit has been exceeded. Insert an if statement that determines whether the new balance exceeds the specified credit limit. If so, display "Credit Limit Exceeded!" in errorJTextField. Otherwise, clear the contents of errorJTextField. g) Opening the Command Prompt window and changing directories. Open the Command Prompt window by selecting Start > Programs > Accessories > Command Prompt. Change to your working directory by typing cd C:\SimplyJava\CreditChecker. h) Saving the application. Save your modified source code file. i) Compiling the application. Compile your application by typing javac CreditChecker.java. j) Running the completed application.When your application compiles correctly, run it by typing java CreditChecker. Use the values shown in the two sample outputs of Fig. 6.33 to ensure that your application performs the credit check correctly. k) Closing the application. Close your running application by clicking its close button. l) Closing the Command Prompt window. Close the Command Prompt window by clicking its close button. v What does this code do? 6.14 Assume that the user has entered the value 27 into ageJTextField. Determine what is displayed in outputJTextField by the following code: 1 2 3 4 5 6 7 int age = Integer.parseInt( ageJTextField.getText() ); if ( age < 0 ) { outputJTextField.setText( "Enter a value greater than or equal to zero." ); } (continued on next page) Tutorial 6 Wage Calculator Application 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 v What’s wrong with this code? (continued from previous page) "Child" ); "Teenager" ); "Young Adult" ); "Adult" ); "Senior Citizen" ); 6.15 The following code segment should display "AM" in ampmJLabel if the hour is a value in the range 0–11 and should display "PM" in ampmJLabel if the hour is a value in the range 12– 23. For any other hour value, the code segment should display "Time Error" in ampmJLabel. Find the error(s) in the following code: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 v Using the Debugger else if ( age < 13 ) { outputJTextField.setText( } else if ( age < 20 ) { outputJTextField.setText( } else if ( age < 30 ) { outputJTextField.setText( } else if ( age < 65 ) { outputJTextField.setText( } else { outputJTextField.setText( } 145 int hour = 14; if ( hour >= 0 ) { if ( hour < 12 ) { ampmJLabel.setText( "AM" ); } } else { ampmJLabel.setText( "Time Error." ); } else if ( hour >= 12 ) { if ( hour < 24 ) { ampmJLabel.setText( "PM" ); } } 6.16 (Grade Converter Application) The Grade Converter application is supposed to input an integer grade between 0 and 100 from the user and display the corresponding letter grade. For values 90–100 the application should display A; for 80–89 the application should display B; for 70–79 the application should display C; for 60–69 the application should display D; and for grades from 0–59, the application should display F. However, when you run the applica- tion you will notice that the application incorrectly displays B for all values in the range 90– 100; the application should display A for these values. Follow the steps below to locate and fix the logic error. Figure 6.34 shows the incorrect output when the value 95 is input. 146 Introducing Algorithms, Pseudocode and Program Control Tutorial 6 Figure 6.34 Incorrect output for Grade Converter application. a) Copying the template to your working directory. Copy the directory C:\Examples\ Tutorial06\Exercises\Debugger\GradeConverter to your C:\SimplyJava directory. b) Opening the Command Prompt window and changing directories. Open the Command Prompt by selecting Start > Programs > Accessories > Command Prompt. Change to your working directory by typing cd C:\SimplyJava\GradeConverter. c) Compiling the application for debugging. Compile the application with the -g command-line option by typing javac -g GradeConverter.java. d) Starting debugging. In the Command Prompt, type jdb. This command will start the Java debugger. e) Setting breakpoints. Use the stop command to set breakpoints at lines 95 and 99. f) Running the application in the debugger. Run the Grade Converter application in the debugger by typing run GradeConverter. Type 95 in the Enter grade (0-100): JTextField, then press the Convert JButton. g) Locating the logic error. Use the debugger’s print and cont commands to help you locate the logic error. When you continue execution from the breakpoint at line 95, notice that execution continues to line 99, which is in the next if statement. If the application logic is implemented correctly, the convertJButtonActionPerformed event handler should terminate after line 95 executes. Open GradeConverter.java in your text editor and scroll to lines 95–99 in the application and fix the logic error. h) Saving the application. Save your modified source code file. i) Compiling the completed application. Compile your application by typing javac GradeConverter.java. j) Running the application. When your application compiles correctly, run it by typing java GradeConverter. Test the application again with the value 95 to ensure that the application displays the correct letter grade (A). k) Closing the application. Close your running application by clicking its close button. l) Closing the Command Prompt window. Close the Command Prompt window by clicking its close button. v Programming Challenge 6.17 (Encryption Application) A company that transmits data over the telephone is concerned that its phones could be tapped. All its data is transmitted as four-digit int values. The company has asked you to write an application that encrypts its data so that the data may be transmitted more securely. Encryption is the process of transforming data for security reasons. Your application should read a four-digit integer input by the user in a JTextField and encrypt the information as described in the steps of this exercise when the user clicks the Encrypt JButton (Fig. 6.35). Figure 6.35 Encryption application. a) Copying the template to your working directory. Copy the directory C:\Examples\ Tutorial06\Exercises\Encryption to your C:\SimplyJava directory. b) Opening the template file. Open the Encryption.java file in your text editor. Tutorial 6 Wage Calculator Application 147 c) Coding the Encrypt JButton’s ActionPerformed event handler. Add the code for Steps d through f to event handler encryptJButtonActionPerformed (lines 139–142). d) Obtaining the user input. In line 141, insert a statement that obtains the user input from numberJTextField, converts it to an int and assigns the value to int variable number. e) Extracting the digits from the user input. Use the programming techniques you used to solve Exercise 5.17 to insert statements that extract the digits from int variable number. Store the digits of number in the int variables digit1, digit2, digit3 and digit4, respectively. f) Encrypt each digit and display the encrypted results. Replace each digit by performing the calculation (the sum of that digit plus 7) modulo 10. We use the term modulo (mod, for short) to indicate that you are to use the remainder (%) operator. Swap the first digit with the third, and swap the second digit with the fourth. Display the encrypted numbers in the corresponding JTextFields: encryptedDigit1JTextField, encryptedDigit2JTextField, encryptedDigit3JTextField and encryptedDigit4JTextField. [Note: Once a number is encypted, it will need to be decrypted in the future. You might consider how to write an application that will decrypt these values.] g) Opening the Command Prompt window and changing directories. Open the Command Prompt window by selecting Start > Programs > Accessories > Command Prompt. Change to your working directory by typing cd C:\SimplyJava\Encryption. h) Saving the application. Save your modified source code file. i) Compiling the completed application. Compile your application by typing javac Encryption.java. j) Running the application. When your application compiles correctly, run it by typing java Encryption. Use the values shown in the sample output of Fig. 6.35 to ensure that your application performs the encryption correctly. k) Closing the application. Close your running application by clicking its close button. l) Closing the Command Prompt window. Close the Command Prompt window by clicking its close button. ...
View Full Document

This note was uploaded on 04/29/2010 for the course CS 5503 taught by Professor Kaylor during the Spring '10 term at W. Alabama.

Ask a homework question - tutors are online