Presentation is loading. Please wait.

Presentation is loading. Please wait.

Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 6 Decisions and Conditions.

Similar presentations


Presentation on theme: "Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 6 Decisions and Conditions."— Presentation transcript:

1 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 6 Decisions and Conditions

2 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 2 McGraw-Hill/Irwin Objectives Read and create flowcharts that show the logic of a selection process. Use if statements to control the flow of logic. Understand and use nested ifs. Evaluate conditions using the relational operators. Combine conditions using the logical operators. Perform validation on numeric fields. Determine the event that caused the actionPerformed method to be called. Understand the precedence and relationship of assignment, arithmetic, logical, and relational operators.

3 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 3 McGraw-Hill/Irwin Decision Statements The decision statements are one of the most powerful statements because it has the ability to make decisions and take alternate courses of action based on the outcome. The decision made by the computer is formed as a question: Is the given condition true or false? If it is true do one thing and if it is false do something else.

4 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 4 McGraw-Hill/Irwin The if Statement-General Form if (condition) statement; [else statement] if (condition) { statement(s); } [else { statement(s); }]

5 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 5 McGraw-Hill/Irwin The if Statement-Examples if (fltHours > 40.0f) { CalculateOvertime(); } if (intGrade >= 70) { lblGrade.setText("Pass"); } else { lblGrade.setText("No Pass"); } if (intAge < 12) CalculateDiscount();

6 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 6 McGraw-Hill/Irwin Decision Statements The curly braces become important when you have more than one statement after the if or else statement. Let us look at Examples: intAge = 12 Example 1:if( intAge < 12) CalculateDiscount(); DisplayDiscount(); Example 2:if( intAge < 12) { CalculateDiscount(); DisplayDiscount(); }

7 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 7 McGraw-Hill/Irwin Decision Statements Continued It is good programming practice to have curly brackets regardless of the number of statements you have in the if or else clauses. If you place a semicolon after the if statement. You will not get a syntax error but the if statement will be terminated after the condition.

8 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 8 McGraw-Hill/Irwin Conditions You can form conditions with numeric variables and constants, character (char) variables and constants, and arithmetic expressions. Note that the relational operator for equality is = = signs, as one equal sign is an assignment operator. If you use an assignment operator in a condition you will receive an error as the condition has to evaluate to a boolean.

9 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 9 McGraw-Hill/Irwin Sample Comparison Section Sample Comparisons int intAlpha = 5; int intBravo = 4; int intCharlie = -5; `4 ConditionEvaluates intAlpha = = intBravofalse intCharlie < 0true intBravo > intAlphafalse intCharlie <= intBravotrue intAlPha >= 5true intALpha != intCharlietrue

10 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 10 McGraw-Hill/Irwin Comparing Data The comparison of one character to another is based on the ASCII code. The comparison of a character with or without single quotes produces different evaluations. For example : chrSex = = ‘F’ // this will compare to the letter F. For example : chrCode != ‘\0’ // this will compare with a null character and not 0. For example : chrCode = = ‘9’ // this will compare to the digit 9.

11 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 11 McGraw-Hill/Irwin For example : chrCode = = ‘9’ // this will compare to the ASCII code 9 which is a tab character. For example : char chrQuestionMark = ‘?’, chrExclamation = ‘!’; The condition (chrQuestionMark < chrExclamation) will evaluate to false. chrQuestionMark has the ASCII value of 63 chrExclamation has the ASCII value of 33 If you wanted to compare individual characters in a string, you can by obtaining a single character with the charAt method. For example : (strName.charAt(0) = = ‘A’) Comparing Data Continued

12 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 12 McGraw-Hill/Irwin Comparing Numeric Wrapper Classes When using numeric wrapper classes you will have to use the equals method to compare the numeric wrapper objects.

13 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 13 McGraw-Hill/Irwin Comparing Strings You can use methods of the String class to compare String objects to String objects or string literals enclosed in quotes. If you are testing for equality, you can use the equals method or equalsIgnoreCase method. If you wish to compare strings in alphabetical order then you need to use the compareTo method. It will compare greater than or less than.

14 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 14 McGraw-Hill/Irwin The Equals Method The string class equals method returns true if the strings are the same and false if they differ. As soon as a character in one string is not equal to the corresponding character in the second string, the comparison is terminated, and condition returns false. Let’s look at an example : String strName = new String(“Joan”); String strName = new String(“John”); (strName.equals(strName2)) will evaluate to false because a has a lower ranking than h in John.

15 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 15 McGraw-Hill/Irwin The equalsIgnoreCase Method Let’s look at an example: String strName = new String(“joan”); String strName2 = new String(“JOAN”); (strName.equals(strName2)); //evaluates to false (strName.equalsIgnoreCase(strName2)); // evaluates to true

16 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 16 McGraw-Hill/Irwin The compareTo Method The compareTo method returns an integer with one of three possible values. If strString1 is greater than strString2, a positive value is returned. If strString2 is greater than strString1, a negative value is returned. To use this method effectively, you can set up a condition using the return value and relational operator.

17 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 17 McGraw-Hill/Irwin The compareTo Method Continued (strString1.compareTo(strString2) = = 0) //Are the strings equal (strString1.compareTo(strString2) ! = 0) //Are the strings different (strString1.compareTo(strString2) > 0) //Is strString1 greater than strString2 What happens when one word is shorter than the other? How does it compare? The shorter word is padded with blanks to have the same length and the comparison begins.

18 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 18 McGraw-Hill/Irwin ASCII Code CodeValueCodeValueCodeValue 0Null38&60< 8backspace39'61= 9Tab40(62> 10Linefeed41)63? 12FormFeed42*64@ 13Carriage Return 43+65-90A-Z 27Escape44,91[ 32Space45-92\ 33!46.93] 34“47/94^ 35#48-570-995- 36$58:96` 37%59;97-122a-z

19 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 19 McGraw-Hill/Irwin The Logical Operators You can test multiple conditions using logical operators to combine conditions. Logical OperatorMeaningEvaluates &&AndBoth conditions must be true for the entire condition to be true. | OrEither condition or both conditions must be true for the entire condition to be true. !NotReverse the truth of a condition. Logical Operators

20 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 20 McGraw-Hill/Irwin Precedence of Logical Operators in Compound Conditions && operator has higher precedence than the || operator and the conditions are read left to right. To alter the order of evaluation, use parentheses. Beware of smart compilers, once they have determined that the condition is false, they will not evaluate the rest of the condition.

21 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 21 McGraw-Hill/Irwin Nested If Statements A. Let us look at example of nested if: if(intAge < 21) { if(chrSex = = “M”) strCategory = “BOY”; else(chrSex = = “F”) strCategory = “GIRL”; } else { strCategory = “ADULT”; } A. First Method: if (intTemp <= 32) { lblComment.setText("Freezing"); } else { if (intTemp > 80) { lblComment.setText("Hot"); } else { lblComment.setText("Moderate); } B. Second Method: if (intTemp <= 32) { lblComment.setText("Freezing"); } else if (intTemp > 80) { lblComment.setText("Hot"); } else { lblComment.setText("Moderate); }

22 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 22 McGraw-Hill/Irwin intTemp>32? intTemp>80? TrueFalse TrueFalse lblComment.Capt ion = “Freezing” lblComment.Capt ion = “Moderate” lblComment.Caption = “Hot” Flowcharting a Nested if Statement

23 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 23 McGraw-Hill/Irwin Conditional Operator You can write decisions using Java’s conditional operator which is the shortcut version of if then else.

24 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 24 McGraw-Hill/Irwin The Conditional Operator – General Format (condition) ? TrueResult : FalseResult

25 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 25 McGraw-Hill/Irwin The Conditional Operator - Examples fltRate = (fltSales < 10000f) ?.05f :.1f; fltCommission = (fltSales < 10000f) ? fltSales *.05f : fltSales *.1f;

26 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 26 McGraw-Hill/Irwin Validating User Input Checking to verify the data entered is correct is called validation. Validation may include making sure that data is numeric, checking for specific values, checking a range of values, or making sure that the required item is entered. We separate the user interface code form the code to handle processing. We check for the input data in the applet class and the business rules in the processing class.

27 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 27 McGraw-Hill/Irwin Checking for Business Rules Often you must check an input value to make sure that it follows business rules. Business rules may be a rate of pay, a check amount, or the amount of hours worked do not exceed a certain limit.

28 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 28 McGraw-Hill/Irwin Validating in a Class So for invalid data the instance variables are set to negative 1. This is one way of indicating bad data, the other is checking with a boolean variable. In the applet that instantiates the processing class, you can check for the instance variables if they passed the validation, to continue processing or not. Using this technique, you properly separate the UI components for the business rules and calculations.

29 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 29 McGraw-Hill/Irwin Passing Variables as Arguments of a Method When you set up a class, you need to decide whether to assign class instance variables in the class constructor or pass the variables as arguments in a method. One drawback is cannot send any values back through a constructor. One of the reasons setting the instance variables to –1 and the get methods to see the value of the variables.

30 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 30 McGraw-Hill/Irwin Passing Variables as Arguments of a Method Continued You can also use boolean variables to indicate bad data. The boolean variable indicates if the input values passed business rules validation. For example: if (myPayroll.blnInvalidRate) //did not pass validation if { //condition is true txtRate.selectAll(); showStatus(“Invalid Data”); }

31 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 31 McGraw-Hill/Irwin Checking for Numeric Values The best way to check for non-numeric data is by catching exceptions. You can also use the isNaN method (is not a number) of the Double and Float wrapper classes.

32 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 32 McGraw-Hill/Irwin Programming with Multiple Buttons For any component that has an actionListener assigned triggers the same actionPerformed method. You need to determine which object triggered the actionPerformed. Java passes an ActionEvent object as an argument to the method, in which you give the argument a name(evt) - actionPerformed (ActionEvent evt). The getSource method on the object will give the name of the object that triggered the event.

33 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 33 McGraw-Hill/Irwin Programming with Multiple Buttons Continued For example: Object objSource = evt.getSource(); The next step is to use a condition to compare the object with the names of your components. For example :if(objSource = = btnCalculate || objSource = = txtHours || objSource = = txtRate) { CalculatePay(); } else { ClearTextFields(); }

34 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 34 McGraw-Hill/Irwin Disabling and Enabling Buttons You can disable a button by graying it out or you can hide a button. It not advisable to hide a button as it frustrates the user. You use the setEnabled method for the enabling and disabling and setVisible method to show and hide.

35 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 35 McGraw-Hill/Irwin The setEnabled Method--General Format object.setEnabled(booleanValue);

36 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 36 McGraw-Hill/Irwin The setEnabled Method--Examples btnCalculate.setEnabled(true) ; btnClear.setEnabled(false) ;

37 Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 37 McGraw-Hill/Irwin Precedence of Operators OperatorAssociation ++ -- * / %left to right* + -left to right =left to right = = !=left to right &&left to right ||left to right ?:right to left +* =+ =/ =/ =- =right to left * Increment and Decrement operators read right to left


Download ppt "Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 6 Decisions and Conditions."

Similar presentations


Ads by Google