1 / 37

Decision Statements in Flowcharts: Logic and Control

Understand how to create flowcharts to depict selection processes using if statements and nested ifs. Learn to evaluate conditions using relational and logical operators, and perform validation on numeric fields.

Download Presentation

Decision Statements in Flowcharts: Logic and Control

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 6 Decisions and Conditions

  2. 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. 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. The if Statement-General Form if (condition) statement; [else statement] if (condition) { statement(s); } [else { statement(s); }]

  5. 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. 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. 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. 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. Sample Comparison Section Sample Comparisons int intAlpha = 5; int intBravo = 4; int intCharlie = -5; `4

  10. 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. Comparing Data Continued • 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’)

  12. Comparing Numeric Wrapper Classes • When using numeric wrapper classes you will have to use the equals method to compare the numeric wrapper objects.

  13. 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. 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. 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. 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. 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. ASCII Code

  19. The Logical Operators • You can test multiple conditions using logical operators to combine conditions. Logical Operators

  20. 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. 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); } 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”; } Nested If Statements

  22. True False intTemp>80? lblComment.Caption = “Freezing” True False lblComment.Caption = “Moderate” Flowcharting a Nested if Statement intTemp>32? lblComment.Caption = “Hot”

  23. Conditional Operator • You can write decisions using Java’s conditional operator which is the shortcut version of if then else.

  24. The Conditional Operator – General Format (condition) ? TrueResult : FalseResult

  25. The Conditional Operator -Examples fltRate = (fltSales < 10000f) ? .05f : .1f; fltCommission = (fltSales < 10000f) ? fltSales * .05f : fltSales * .1f;

  26. 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. 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. 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. 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. 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(); • txtRate.selectAll(); • showStatus(“Invalid Data”); • }

  31. 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 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 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. 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. The setEnabled Method--General Format object.setEnabled(booleanValue);

  36. The setEnabled Method--Examples btnCalculate.setEnabled(true) ; btnClear.setEnabled(false) ;

  37. Precedence of Operators * Increment and Decrement operators read right to left

More Related