Presentation is loading. Please wait.

Presentation is loading. Please wait.

Decision Making and Repetition with Reusable Objects

Similar presentations


Presentation on theme: "Decision Making and Repetition with Reusable Objects"— Presentation transcript:

1 Decision Making and Repetition with Reusable Objects
Chapter 4 Decision Making and Repetition with Reusable Objects

2 Objectives Design a program using methods
Code a selection structure to make decisions in code Describe the use of the logical AND, OR, and NOT operators Define exceptions and exception handling Selection structure such as if…else

3 Objectives Code a try statement and a catch statement to handle exceptions Create a user-defined method Code a repetition structure using the while statement Write a switch statement to test for multiple values in data

4 Objectives Format numbers using a pattern and the format() method
Construct a Color object Use a Checkbox and a CheckboxGroup in the user interface

5 Introduction Control structures alter the sequential execution of code
Selection structure If - else, Case Repetition structure While, For, Until User-defined methods break tasks into reusable sections of code - modules Exception handling in Java allows for the testing of valid and accurate input Programs normally execute sequentially. A programming language would be virtually worthless if it could not modify this behavior. Selection Structure: If – Else Repetition Structure: While, Until User Defined methods allow the user to break their code up into small pieces, sometimes called modules. These modules can then be tested independently of other and reused over and over Many kinds of errors in programming are called Exceptions. For instance, entering numeric data when string data is expected. Java allows for the interception of many errors, called Exception Handling.

6 The Sales Commission Program
Calculate sales commission for agents in a travel agency Coded as a console application and an applet Input The user chooses from three types of commission codes The commission code identifies the type of sale and the commission rate The user enters a sales amount Calculate commission and display output The programs developed in this chapter will calculates a Sales Commission based on input from the user. Telephone sales receive a 10% commission In-Store sales receive a 14% commission Outside sales receive an 18% commission We’ll develop a console application to do this, then convert the console application to an Applet that will use text boxes and option buttons for user input.

7 User’s Request for a new program.

8 Program Development Problem analysis Design the solution
Each user decision corresponds to a program task Develop and test each task before adding it to the program Design the solution Design storyboards for the two user interfaces Program design Design a flowchart consisting of required methods Write related pseudocode for each method Validate Design Program Development Cycle – book goes into more detail

9 Flowchart and Pseudocode.
Have students follow the instructions in on page 224, figure 4-5. This will have them open TextPad and create a new program file on their floppy disk

10 Coding the Program Code the program using program stubs
Stubs are incomplete portions of code that serve as a template or placeholder for later code Stubs allow ease in debugging through incremental compilation and testing Import java.swing.JOptionPane Import java.text.DecimalFormat Formats decimal output into Strings Declare variables Compile and test the program stub A Program Stub, which really doesn’t do anything. It simply invokes other methods. This allows the programmer to build and test the programming incrementally. Most Java programs contain certain pieces of code at the beginning of every program: comments, import statements, the class header, and the main method header. These items, along with certain variable declarations are used to build the program stub. Programmers, will frequently Cut/Paste/Tweak code from an existing program to start the program stub of a new program. Reworded 1st paragraph from: A Program Stub, sometimes called a Program Driver, is a piece of code, usually the first piece of code, which really doesn’t do anything. It simply invokes other methods. This allows the programmer to build and test the programming incrementally.

11 Coding the Program Import javax.swing.JOptionPane; Allows you to use its methods to create and display dialog boxes that display messages and prompt users for input. Import java.text.DecimalFormat; Will allow you to format the output with dollar signs, commas, and periods. The computer only works with raw numbers. In any programming language it’s up to the programmer to format the output. ,000 $10,000 $100.00 An oversimplification here, but the same number in memory could be formatted to appear in various different forms. There will be 3 variables required in this program: one to hold the sales amount, one to hold the calculated commission, and one to hold the commission code – this code will determine what the sales commission percentage will be. Have students follow the instructions on Page 226, figure 4-7, to code up the program stub. Remind students, again, that Java is Case Sensitive, and that the class name must match exactly the file name for the source code. Have students follow instruction in grey box on Page 227. This will have them compile the program stub.

12 Writing Methods A program with modules allows for clarity, reusability, and refinement The code for each module can be separated into programmer-defined methods The main() method transfers execution to the methods through a call statement The called method returns control to its caller with the return statement or the ending brace The return statement returns any required data back to the calling method “Modularity is a characteristic of a program in which a larger program's source code is broken down into smaller sections, or modules, of source code.” This modularity facilitates ease of testing and debugging, as well as modification and reusability. Essentially, the main program is nothing more than a series of calls to other modules. The Return statement in the subroutine will return any required information back to the calling method. For instance, if the subroutine is used to calculate a commission, this commission will be passed back to the calling method via the Return statement.

13 Calling a Method When you need to access a method, you must Call it.
1.) callMethod(); //no arguments 2.) callMethod(argument); // with one argument 3.) callMethod(arg1, arg2); //args separated by commas 4.) firstMethod(secondMethod)); //method used as argument 5.) returnValue = callMethod(argument); //method returns value 1.) finish(); 2.) displayOutput(answer); 3.) getCommission(sales, rate); 4.) System.out.println(output()); 5.) salesTax = getTax(sales); From Table 4-3 on page 228 The PP presentation was apparently missing 2-4 slides. I created this one from book. Upper portion of slide is general format, bottom portion is specific example When you need to utilize the code in a method, you need to call the method. Many programming languages actually have a call command: call finish(). In Java a method is called simply by invoking it as in: finish(); This adds a great degree of flexibility to Java because, as in the 4th example, a method can be passed directly as a parameter to another method without having to code: call. The finish() method has no arguments, it’s probably going to just terminate the program displayOutput(answer) will use the variable named answer as its argument and display that answer on monitor getCommission(sales, rate) will receive 2 arguments, a sales amount and a commission rate. It will then calculate how much commission the person receives. System.out.println(output()) wraps the println() method around the output() method. In this case the output() method will perform its functionality and return a value which will then be displayed on the screen by the println() method salesTax = getTax(sales); It’s very common for a method to perform a function designed to return an answer. In this case, the getTax method will use as an argument the sales variable and return a value which will be set in the salesTax variable.

14 Coding a Method Start by building the Method Header
Follow Method header with open curly brace Follow curly brace with method code, followed by closing curly brace public static double getSales() { Method code } Also created this slide from scratch. The getSales() method has two modifiers public – The access modifier, public, indicates that this method can be accessed by all objects and can be extended or used as a basis for another class. static - The method modifier, static, indicates that get(Sales() is unique and can be invoked without creating a subclass or instance. double - When a method is going to return a value, the 3rd modifier indicates what kind of value that getSales will return. Double indicates that the value to be returned can hold up to 15 decimal points (see pg 140 for chart of data types) A variable of type, double, will have to be defined in the pgm. getSales() The name of the method. This indicates that getSales() will not be passing any arguments, i.e. nothing inside of parenthesis. Some methods can get to be very long. A common programming trick is to code the closing curly brace immediately upon coding the opening one and then inserting your code in between. It helps you to keep track of your braces.

15 Coding a Method double sales = 0.0;
String answer = JOptionPane.showInputDialog(null, “Enter sales amt or click cancel to exit:”); sales = Double.parseDouble(answer); return sales; Also created this slide from scratch. In the getSales() method: Define the variable that will be returned to the calling method. Use the showInput dialog box to get data from the user. First parameter, null, indicates that dialog box should be placed in the middle of the screen (doesn’t always seem to work this way) Since all data entered from the keyboard is in string format, use the parseDouble method to convert the string variable, “answer” into the double variable, “sales.” Return the value of sales to the calling method. Have students complete the instructions in the gray box on page 230 Warn students that in this chapter they have to be very careful about line numbering. The previous chapters always had students add code to the end of the program. In this chapter we will frequently be adding code to the middle of the program. This could get confusing. And wrong placement of code can lead to very confusing compile errors. Be very careful to adhere to the line numbering in the book. In this case they are told to code line 20. Line 20 already exists, so they are actually inserting a new line 20. The new line 20 should be a blank line. Have students complete the instructions in figures 4-9,10 on pg 231 Have students complete the instructions in figure 4-11 on pg 232 to compile and test the code.

16 The if-else clause is known as the selection structure.
“The function of the selection structure is to state a condition that allows a program to choose whether to execute one or more lines of code.” (pg 233) The format of the if statement is such that it is followed by a condition in parenthesis. The condition is evaluated for true or false. If true, the statement, or block of statements in curly braces, are executed. If the condition is not true, the code is not executed and the system checks for the existence of an else clause. The else clause is optional and does not have to be included. There is no Then clause in Java. Point out that statements like x = x while not algebraically correct are valid in programming languages. Point out flow of control. If logic evaluates to false, then flow of control falls through to after the closing curly brace. Point out what happens if else is removed: If (age >= 65) { code = “S”; text = “Senior Citizen discount”; } else code = “A”; text = “Adult price”; If you remove the else clause, the second block will always execute whether age is > = 65 or not:

17 The if…else Statement Single: line 30, line 31
Mention to students that this code appears in Figure 4-12 on page 235 is not part of the program we are building. It is just there to illustrate the if-else concept. They probably shouldn’t have included it in the same kind of boxes as the program code. If/Else clauses can be Nested. In this example, the If/Else logic contained in lines 17 through 26 are nested within lines 16 to 27. If the test for age is false, that is if age is <= 21, then the logic for testing whether age is > 64 will never be tested. It is common practice to indent nested code. This makes it much easier to follow the program logic. Some programmers like to put blocks around even single if statements. For one thing it facilitates future expansion. If (age > 12) { System.out.println(“Teen”); } Execution of nested code depends upon the evaluation of the outer logic. I.E. If the outer logic is false, the inner logic never gets evaluated. Single: line 30, line 31 Block: lines 16-27, lines 18-21, lines 23-26, lines 29-32 Nested: lines 17-26, lines 30-31

18 List of Operators used in the evaluation of If clauses.
Point out that the examples do not reflect the fact that these operators are always used within the context of an if statement. Next slide has some specific examples. First 2 are Equality operators, the next 4 are Relational operators, and the last 3 are Logical operators. Logical operators are used when you want to test for more than one condition. Be careful to use the double equal sign == when testing for an equal condition. Using only 1 = will result in a compile error. Very common error

19 Testing with an if statement
Testing a single condition if (!done) if (answer == null) Testing multiple conditions if ((gender == “male”) && (age >= 18)) if ((age < 13) || (age > 65)) AND and OR expressions evaluate the right operand only if the left operand is not sufficient to decide the condition The Not operator is usually used to test a Boolean condition. In this example the variable done would have a Boolean value of True if processing was completed, and False if processing was not complete. In java null is a constant that represents the presence of no data. It’s not the same as a blank or a zero. Blanks and Zeros take up memory. A null takes up no memory. string answer = JOptionPane.showInputDialog(null,“Enter sales amt or click cancel to exit:”); (dialog box will have an ok and a cancel button) If (answer == null) finish(); If cancel was clicked, the finish method will be called, and the finish method will simply end the program. If ok was pressed, input will be processed. Note, that if a null is entered there is no point to translating the string entry to a numeric, therefore the test for null occurs before the setting of the sales variable. Have students follow the instructions on page 237, figure This will have them test for a valid sales amount Then have them complete the instructions on Page 238, figure 4-15 and Remind them again to be very careful of line numbering. Follow the directions explicitly.

20 Exception Handling An exception is an event resulting from an erroneous situation which disrupts normal program flow Exception handling is the concept of planning for possible exceptions by directing the program to deal with them gracefully, without terminating Three kinds of exceptions I/O Run-time Checked The compiler checks each method to ensure each method has a handler It’s certainly not possible to anticipate every conceivable error that can occur in a program. But we want to anticipate as many as possible. For instance, if you do a divide in your program, it’s certainly possible that you may accidentally try to divide by Zero. This would cause a run-time error. This kind of exception can be caught in advance. When a run-time error occurs, the system looks to see if you have coded a way to handle the exception. If you have not, the system will handle the exception in its own way – often just terminating the program. A checked exception is one in which you have coded the routine necessary to handle the exception.

21 Handling Exceptions The try statement identifies a block of statements that may potentially throw an exception The throw statement transfers execution from the method that caused the exception to the handler Transfers execution to the catch statement if the throw is placed within a try statement The catch statement identifies the type of exception being caught and statements to describe or fix the error The finally statement is optional and is always executed regardless of whether an exception has taken place Placed after the catch statement When an exception occurs, that exception is said to be thrown. The try statement identifies a statement or block of statements that might potentially throw an exception. If an exception occurs, control is immediately transferred to an exception handler. Let’s say you’re going to do a division. You might want to encase the code within a try statement try Put up the division then encase within try statement { average = sum / quantity; } stmt will execute the same with or without try with try, if error then exception will be thrown to a catch stmt When an exception occurs within the try code, execution gets transferred to a catch statement. The catch statement contains the code to handle the exception. Thus the catch statement should immediately follow the try statement (according to another book, I don’t think this is an absolute) catch(DivideByZeroException divide_err) { appropriate code – maybe you want to give the user a chance to re-enter data} You can force a particular exception to be triggered with the throw statement. You might want to do this for data validation. For instance, if you ask the user to enter a number between 1 and 100, and they enter 150, this is not technically an exception. However, if you throw this exception you can write the code that will handle the condition. You might use the finally statement for cleanup routines. The book does not have an example of using finally. Note: throw is not the same as throws. When we code throws on the method definition, we are saying that the method may potentially cause a particular kind of exception. And if it does, we are throwing the error back to the routine that called the method. In the case of the main method, we would be throwing the exception back to the operating system.

22 Book CHEATS. DivideByZero has to be a User Defined Exception
Book CHEATS! DivideByZero has to be a User Defined Exception. No time to teach/learn how to incorporate it. They should not have included non-standard code. I think the example is not too clear. Under the try example they are giving two different examples. One, of the system generating the exception, and one where the programming is generating it with a throw. You would not normally have both these lines of code together. In this example you could do it either way: let the system throw it or throw it yourself, in other cases it may not be an either or condition, for instance after you’ve calculated a value and you want to check if that value is within a certain range. And the second example is unclear. You would normally code the throw statement inside of an if statement. (Leave space on board to put a catch statement underneath) Try { if (divisor == 0) throw new DivideByZeroException(); answer = 23 / divisor; } In this case the answer statement will not execute if the divisor was zero because an exception would have been thrown. The try statement tells the JVM that you plan to deal with runtime errors as checked exceptions, rather than let the system handle them. In order to explicitly throw an exception you need to construct a new instance of a standard Java exception object, in this case DivideByZeroException.

23 General format of catch statement.
Try { if (divisor == 0) throw new DivideByZeroException(); answer = 23 / divisor; } catch(DivideByZeroException dividerr) (defining variable dividerr, of { type: DivideByZeroException) the code you want to have execute will appear here

24 Exception Example Without an exception handler, a divide by zero would cause: Exception in thread “main” java.lang.ArithmeticException: / by zero With an exception handler: try { average = total_grade / total_students; //assume total_students=0 } catch (DivideByZeroException() System.out.println(“A Divide by zero occurred when dividing total_grade by total_students. Program aborting.”); finish(); // Close program nicely by calling your finish routine Now we would see: A Divide by zero occurred when dividing total grades by total students. Program aborting. I created this slide to supplement example on next slide.

25 Catch an exception Throw an exception
A NumberFormatException can occur when your numeric data is not in the format expected. For instance if you’ve defined a variable as an Integer and the user enters a decimal point. This will cause a NumberFormatException In the first example, if the user does not enter a number of the type double – for instance if he enters “Five Thousand”, a NumberFormatException exception will be generated and caught by the catch statement. You can make use of these Standard Java Exceptions for yourself. In the second example the sales amount has to be greater than zero. If it’s not, we explicitly throw a NumberFormatException and it will be caught and handled by the same catch statement. (They should have coded the same catch statement in second example) Note: they coded 2 examples of try statement to illustrate that the catch can actually catch two different kinds of errors. First, if the parse fails, the catch will kick in and, second, if the if fails the catch will also kick in. You can also create your own exceptions. For instance, if you wanted to make sure that the user enters an 8 character password you could create a new class (creating a new class is beyond the scope of this class) And then throw that exception elsewhere in your code: throw new WrongPasswordException(); No need to go into more detail. The book just mentions this, but doesn’t give an example Throw an exception

26 Testing methods Compile the program after coding each method and call statement Run the program with correct input Run the program to test the exception handling with invalid input Alphabetic data Negative values Null or zero values Verify that the user is allowed to reenter data Verify the program closes correctly It’s very important to test both valid and invalid data Have students follow the instructions on Page 243 in figure This will have them code the try and catch statements. Remind students, again, to be careful of their numbering. Have students follow the instructions on Page 244, figure This will have them include the test for negative sales in their NumberFormatException routine. Have students follow the instructions on Pages 245 thru 246 in figure Have them pay particular attention to the different data that the book wants them to enter. It’s important to test the validity of all your routines.

27 Repetition Structure Up to now, we have not been able to repeat any commands. For instance, if the user enters wrong data, our program terminates. It would be better to give them another chance. This can be done through Looping with a Repetition Structure, in this case the While Repetition structure. while (condition) NOTE: No semicolon after while condition! { code } All commands within a while construct will execute as along as the condition is true. The condition must be a Boolean expression that evaluates to true or false. int ctr=10; while (ctr > 0) { System.out.println(“ctr = “ + ctr); ctr = ctr -1; See java_programs/examples/_05_chp4_simple_while.java for example.

28 The getSales() method You can also have a straight Boolean expression coded in your while: Turn head sideways and scrunch eyes. If done is false then !done should be true, but it doesn’t work that way. boolean done = false; While (! done) // Loop while value of done is not true, see pg 248 Example on top of page 248 is wrong for a couple reason. You can’t test for answer that way and you can’t just say “done” Comparison of strings is tricky in Java. You have to use methods which are beyond the scope of this book. Briefly, if you wanted to compare strings the correct code would be. if (answer.compareTo(“yes”) == 0) done=true; See java_programs/examples/StringCompare for example that illustrates both the !done logic, as well as the compareTo method. The if code in this example works: if (answer == null) finish(); because null is a special case, it is not a string, it is a special reserved word, so we don’t have to use the compareTo() method. Have students follow the instructions on Page 249, figure 4-23 Then have students follow the instructions on Page 250. This will have them compile and test the program to this point using specific test data.

29 The getCode() method After obtaining a valid sales amount, we now need to get a commission code. We do this by creating a new method called getCode() Step through logic using the projector. Note that the variable done is used again in line 62. This is valid because by default variables are local in scope. That is, the variables are known only in the method they are defined. Line 64 sets up a try condition so that it can capture invalid code. Line 68 displays message to user in a dialog box, and returns their answer to variable code. Integer.parseInt is required because data returned from keyboard is character and must be converted to numeric. Line 71 uses logic OR to test for invalid commission codes and throws a NumberFormatException if there is a problem. If no problem then done variable is set to true so that loop can stop executing. Line 74 catches the format exception Line 79 returns the commission code entered back to the main method. Have students follow the directions on page 252, figure 4-25 Then have students follow the directions on page 253 which will compile and test the getCode segment of pgm.

30 The Case Structure A type of selection structure that allows for more than two choices when the condition is evaluated Used when there are many possible, valid choices for user input The code evaluates the user choice with a switch statement and looks for a match in each case statement Each case statement contains a ending break statement which forces exit of the structure The switch and case statements tend to simplify complex if else logic. Often used in menu style applications where the user has a choice of several options. Anything you can do with the switch/case statements you could do with if/else statements if you wanted to. General format: switch (some-value) // value must evaluate to an integer expression. { case 1: Do something; Do some more; break; case 2: Do something else; case 3: Do a different thing; default: Do something if value does not match; // default is optional } When some-value = 1 the first case executes. When some-value = 2 the second case executes. When some-value = 3 the third case executes. If value is not equal to 1, 2, or 3 the default will execute. Break statement is coded to force an exit from the switch structure. You can have as many cases as you want, thus facilitating complex choices

31 Essentially what I had on last page
Essentially what I had on last page. Emphasize, again, that in this example flavor must evaluate to an integer.

32 The getComm() Method public static double getComm(double employeeSales, int employeeCode) This is the method header: public indicates the method is accessible to everything in the program static indicates that the method can be invoked independent of any object double indicates the data type that will be returned from the program getComm is the name of the method we are defining double employeeSales defines a data item of type double which corresponds to the variable dollars in the main program int employeeCode defines a data item of type int which corresponds to the variable empCode in the main program. Note that we define commission in the subroutine and use it on the return statement. Back in the main program, the variable, answer, will be set to the value that was in commission. Have students follow the instructions on Pages 256 and 257, figures 4-28 and 4-29 Be careful of line numbering.

33 Arguments and Parameters
When a method is called, the calling method sends arguments; the called method accepts the values as parameters Different but related identifier names for the arguments and the parameters should be used for good program design The variables are only visible in their respective methods Arguments and parameters for a called method and the calling statement must be of the same number, order, and data type In our program, the main method is going to call a method to calculate a sales commission. Main is going to pass two arguments: a sales amount, and an employee code to the getComm method. The getComm method will accept these arguments as parameters. The main method will have to define the variable types to be passed. The getComm method will have to accept parameters of the same type. Generally, different, but related, names are used for the variables in the main program and the subroutine. For instance, if we were creating a subroutine to create the factorial of a number that is passed to it. In our main method we might code: int number=10, answer; answer = calcFactor(number); In our subroutine we might then code: public static int calcFactor(int inNumber); Number, defined as an integer in our main method, corresponds to inNumber in the subroutine, and is also defined as an integer.

34 Formatting Numeric Output
The DecimalFormat class formats decimal numbers into Strings for output Supports different locales, leading and trailing zeros, prefixes/suffixes, and separators The argument is a pattern, which determines how the formatted number should be displayed Performing I/O, especially formatted numeric I/O is a complex process in any programming language. As we’ve seen, the println() method and the JOptionPane() method will allow you to print numbers, but they will not be formatted with $ , . Etc. The DecimalFormat() class will allow you to format decimal numbers into Strings for output. It does so by using a pattern to define how you want to output to look. When defining your pattern: # represents any digit, but will truncate leading or trailing zeros 0 represents any digits but will not truncate leading or trailing zeros , represents a placeholder for a comma in the output field . represents a placeholder for a period in the output field. $ represents a placeholder for a dollar sign in the output field.

35 On example 2 since there are more characters than patterns to the right of the decimal point, rounding occurs. However, since there are more characters than patterns, the pattern matches the first 3 and then leftover numbers just print. You use the format() method to assign the formatting pattern to a specific value double number= ; DecimalFormat pattern1 = new DecimalFormat(“$###,###.##); System.out.println(pattern1.format(number)); The output will look like: $1,234, Note rounding, note 2 leading commas See: java_programs\examples\PatternMatching.java for example

36 The output() method We will now code a method called output to display our sales and commission in a nicely formatted output. We will send two arguments to the subroutine (answer and dollars which correspond to sales and commission) The subroutine will not return a value. Stmt 109 constructs a new DecimalFormat object named twoDigits this will contain the pattern for formatting the sales and commission. Statement 111 is probably the most complicated statement we’ve seen so far. Step through this statement slowly. We are using showMessageDialog to display our Literals: “Your commission on sales of” Formatted sales: twoDigits.format(sales) Formatted commission: twoDigits.format(commission) “Commission Totals” is the 3rd parameter (count the commas) of showMessageDialog – this is the dialog box header. JOptionPane.INFORMATION_MESSAGE is the 4th parameter to showMessageDialog indicating what kind of dialog box it is. Have students follow the instructions on Page 259 and 260, figures 4-31 and 4-32

37 The finish() method Exits system when program completes successfully
We coded the finish() method earlier in the book. We now have to make sure that the main method calls finish to terminate the program nicely. Without a clean termination your console window will remain open. Have students follow the directions on the two gray boxes on Page This will have them code the invocation for finish() and then compile and test the application. This is as far as we will go in the Fall 2006 semester. I may not have gotten to cover the last couple of slides.

38 Done for this semester! This is as far as we will go in this semester. Unfortunately, I may not have gotten to cover the last couple of slides.

39 Moving to the Web Create the host document to execute the applet
The next thing we are going to do is convert the console application to an applet In preparation for doing this we need to create the HTML driver. Have students follow the direction on Page 263 to create a new HTML driver page.

40 Coding an Applet Stub Enter general block comments
Import java.awt.*, java.applet.*, java.awt.event.*, and java.text.DecimalFormat Implement the ItemListener interface to listen for the user choice on a Checkbox Code the method headers for the init() and the itemStateChanged() method itemStateChanged() is an ItemListener method to process user choices Declare variables and construct a Color object The Applet stub will require certain classes to be imported java.applet: which allows the applet to inherit various attributes and manipulate classes. Java.awt is commonly imported for applet used for creating user interfaces and for painting graphics and images. It also allows for the creation of Buttons, TextFields, and Labels java.awt.event provides interfaces and classes for dealing with different types of events that get triggered. It includes such interfaces as the ActionListener (listens for events such as clicking mouse or pressing enter key) and the ItemListener. (listens for events such as the clicking of check boxes) java.text.DecimalFormat will allow you to format your output fields. The code for the applet will be significantly different enough from the console application that the book has you start a new program. They suggest that there is some cut/pasting that you can do from the old application. I found that there wasn’t enough for me to bother with. I found it easier just to code up the new program. Have students follow the instructions in both gray boxes on Page 265, figure 4-38 to code up the stub, and compile and test it.

41 There are a number of colors that are automatically available to you by name. Table 2-9 on page 2.55 give you some of the pre-coded names. However, it’s also possible for you to define your own custom colors. There is a method named color() that takes 3 arguments and will allow you to construct a new color object. Color darkRed = new Color(160, 50, 0); The parameters represent various weights to be applied to the colors Red, Green, and blue. By modifying these numbers you can come up with thousands of various colors. There are lots of Web site that list out some of the color combinations. Unfortunately most of them are in Hex. I found one in decimal, but it’s a little hard to read: Hex version: Dec version: Have students follow the instructions on Page 267, figure 4-41 to declare variables and construct a color. Be careful of line numbers.

42 Making Decisions in Applets
Use a CheckboxGroup to allow user choices Applets support the traditional if/else statements as well as the switch/case statements. However, now that we are in an Applet environment, there are other methods for making decisions One of these is the Checkbox whereby the user is given a selection of boxes that they can check off. There are two flavors of Checkboxes. The traditional Checkbox allows you to check off as many boxes as you want. For instance you could have 4 check boxes indicating 4 different kinds of fruit: apples, bananas, pears, oranges. The user could be asked to check off the types of fruit that they like. Anywhere from 0 to 4 boxes could be checked A grouped Checkbox is one where the choices are mutually exclusive. For instance, you could have a grouped Checkbox reflecting marital status: single, married, divorced, widowed. In this case only one box can be checked off. Checkbox appleBox = new Checkbox (“Granny Smith Apple”) //Define a variable named appleBox with a caption of: “Granny Smith Apple” //We tend to name our variables so they indicate they are a checkbox: appleBox CheckboxGroup maritalSatus = new CheckboxGroup(); Checkbox singleOpt = new Checkbox(“Single”, true, maritalStatus); Checkbox marriedOpt = new Checkbox(“Married”, false, maritalStatus); //Define a CheckboxGroup called maritalStatus //Define two Checkboxes that belong to the maritalStatus group. //The Single box has a caption of “Single” and its state is set to true, so it will be the one selected by default. Only one box in a group can have a true state.

43 Constructing Applet Components
Construct Labels for input and output Construct a CheckboxGroup for user options Frequently we do not want a default option for a grouped checkbox to be displayed to the user. For instance, we may not want to just assume that they are either single, married, divorced or widowed. A common technique to handle this is to create an extra option, which is hidden from the user’s view. In this case, we’ve created a Checkbox called hiddenBox and have set it’s state to true. We will not load this object into the applet’s user interface, thereby making it not appear to the user. We now need to add the code to the applet to construct Labels for prompts and output, a TextField in which the user will enter the sales amount, and a CheckboxGroup for the three sales code options. Have students follow the instructions on Page 270, figure 4-43 to code the labels and checkboxes.

44 Adding Components Add Labels and CheckboxGroup to the applet
Add an ItemListener to each Checkbox component with the addItemListener() method Add color with the setForeground() and the setBackground() methods Set the insertion point with the requestFocus() method We now need to add each of our components such as our labels and Checkboxes to the Java Applet interface via the init method. This will initialize the Applet environment running within the browser. Then we need to notify the Applet to pay attention to any changes by adding an ItemListener to each of the Checkboxes. Then we’re going to change colors and change the focus Focus indicates the currently selected object on a Window. For instance, if you have 3 text boxes on a screen, whichever textbox displays the cursor has the focus. You can control what object has the focus. Whatever object has focus will be the default object and will be associated with the enter key. That’s why if an OK button has focus, you can either click the button, or press enter. In this case we are going to want our sales textbox to have the focus: add(salesField); salesField.requestFocus();

45 The init() Method Since the overall screen can have a background and foreground color, and individual objects can have a background and foreground color, We typically code the colors for the screen first, and then the colors for the individual components as we add them. Note, that we did not add the hiddenBox object to the init method. This is why this box will not be displayed. It’s important to note that components will appear on the screen in the order that we add them. Run java_programs/examples/InitOrder1 and InitOrder2 to show how changing the order that you code in the Init section will change the way things look on the output screen. Have students follow the instructions in gray box on Page 273 to code up the Init method. Then have them follow the directions on Page 273 thru 275 to compile and test the init() method.

46 Handling Exceptions Check for valid data when the itemStateChanged() method is triggered, which happens when the user clicks an option button When the user clicks one of the checkboxes, the ItemListener changes the state of the component. That means that the itemStateChanged() method is triggered. It looks like there is an implied correlation between the ItemListener listening for a change in the state of the item and triggering the itemStateChanged() method. The itemStateChanged() method includes the code to get the sales amount and employee code, and then determine the commission amount. Since we want to check for valid data, this code uses the try and catch statements. If an error occurs, line 69 will set the state of the hiddenBox to true. Since only one checkBox can be true at a time, this will automatically reset all of the other checkBoxes to false, which will make all of them appear without a selection. Line 70 will reset the input field: salesField to blanks and Line 71 will move the focus back to salesField. Have students follow the directions on Page 277, figure 4-51, to code the itemStateChanged method using the try and catch statements. Error Line 66 S/B: catch(NumberFormatException e)

47 The getSales() Method Parse the data from the TextField and return a valid sales amount or throw an exception to the init() method The getSales method will be used to get the sales amount from the user. Reading backwards, the getText() method of the salesField object will obtain the input from the user. Since the input will be in character format, it needs to be converted to numeric. The parseDouble() method will convert the character data to numeric and set the variable sales to that amount. Line 79 checks to make sure that the number entered is not less than zero. If it is less than zero it throws a NumberFormatException which will be handled by the catch statement. Have students follow the directions on Page 278, figure 4-53, to code the getSales() method.

48 The getCode() Method Initialize the code to 0
Use nested if statements to assess the boolean state of the Checkboxes and return the code to init() This version of the program uses a slightly different method for determining the commission code. The getCode() method initializes a variable named, code, to zero. It then uses nested if statements to determine the value that the commission code should be set to. Have students follow the directions on Page 279, figure 4-55, to code the getCode() method.

49 The getComm() Method Identical to the application
Return the commission value to init() The getComm() method is identical to the one used in the previous program. It receives two parameters, the sales amount and the commission code. It then uses a switch/case construct to determine how much the commission should be and returns that value to the calling program via the return statement. Note, that double, defined on the method definition indicates that getComm will return a value of type double: commission. Have students follow the instructions on Page 280, figure 4-57, to code up the getComm() method.

50 The output() Method Send output to the Label using setText()
Construct and use DecimalFormat, using the special character # to make a leading zero absent The output() method is also identical to the previous program. We define a new pattern using the DecimalFormat method, to define a new pattern to print our output with dollars, commas and decimal points. Have students follow the instructions on Page 281, figure 4-59, to code up the output() method.

51 The paint() Method Display a graphic
The paint method is identical to the previous program. It is used to display the Dollar sign image. Have students follow the directions on Page 283, figure 4-61, to code the paint method.

52 Compiling andTesting the Applet
Compile the applet Execute the applet using AppletViewer Test exception handling by clicking an option button and then typing invalid data into the text box Verify the error message and the data clearing mechanisms Test all options with valid data Test in a browser window Document the applet interface and source code Have students follow the directions on Pages 283 thru 285 to compile and test the complete application. Note that there is a confusing statement in number 4 on pg 284. The comment in italics should be with number 5. In fact, due to the nature of the test. I think it would be best for students to close and start the applet over after step 3. Otherwise, it’s a little confusing.

53 Summary Repetition Structures Selection Structure Exception handling
while statement Selection Structure if…else statement switch and case statements Exception handling Try and catch statements Modularity Smaller segments of reusable code through methods Program clarity and refinement

54 Summary Program stubs CheckboxGroup Responding to user options
Incremental testing CheckboxGroup User options for user interfaces Responding to user options ItemListener, addItemListener(), itemStateChanged() Data validation and error messages Testing invalid data

55 Chapter 4 Complete


Download ppt "Decision Making and Repetition with Reusable Objects"

Similar presentations


Ads by Google