1 / 40

CS 303E Lecture 6 Selection / Conditionals: if and if-else statements

CS 303E Lecture 6 Selection / Conditionals: if and if-else statements. As soon as questions of will or decision or reason or choice of action arise, human science is at a loss. Noam Chomsky. Statement_1. Statement_2. Statement_3. Linear flow of control.

Download Presentation

CS 303E Lecture 6 Selection / Conditionals: if and if-else statements

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. CS 303E Lecture 6Selection / Conditionals:if and if-else statements As soon as questions of will or decision or reason or choice of action arise, human science is at a loss.Noam Chomsky Selection:if and if-else statements

  2. Statement_1 Statement_2 Statement_3 Linear flow of control In method button clicked, all we have seen so far is one statement after another: The program must execute each statement in the order written. It can’t decide what to do next. radius = radiusField.getNumber(); area = 3.14 * radius * radius; areaField.setNumber (area); areaField.setPrecision(2); From CircleArea Selection:if and if-else statements

  3. Statement_1 true Statement_2 Condition false Branching = making decisions If the condition is true, execute statement_1; otherwise, execute statement_2: The condition is an expression that can be true or false, such as: x > 0 Selection:if and if-else statements

  4. balance = balance + interest; true balance > 0 balance = balance – penalty; false Branching example An example for a checking account: The account gets interest or a penalty depending on whether the balance is over 0. Selection:if and if-else statements

  5. true Statement Condition Empty false branch If the condition is true, execute statement; otherwise, do nothing: Condition is an expression that can be true or false. false Selection:if and if-else statements

  6. Syntax -- if Statement if (condition) // one-way branch statement1; statement2; statement3; if (condition) // two-way branch statement; else statement; Selection:if and if-else statements

  7. if Statement Examples if (sales > 5000) commission = commission * 1.1; if (balance > 0) { interest = balance * INT_RATE; balance = balance + interest; } else { balance = balance - penalty; } Selection:if and if-else statements

  8. Compound Statements Often, one statement; isn’t enough. So use a compound statement : { statement; . . . zero or more statements statement; between braces {…} } Selection:if and if-else statements

  9. if with Compound Statements if (condition) if (condition) { statement; { statement; . . . . . . statement; statement; } } else { statement; . . . } Selection:if and if-else statements

  10. Example // Pay at payRate with time and one half for // overtime: pay = hoursWorked * payRate; if (hoursWorked > 40) { overtime = hoursWorked - 40; pay = pay + overtime * (payRate / 2); } Selection:if and if-else statements

  11. Conditions orBoolean Expressions Condition is another name for boolean expression -- an expression that evaluates to true or false. One form of condition is expression relop expression where relop is a relational operator. Selection:if and if-else statements

  12. Boolean Relational Operators Math Name Java Java Example = equal = = balance = = 0  not equal != answer != ‘y’ > greater than > expenses > income  greater than or equal >= points >= 60 < less than < pressure < max  less than or equal <= expenses <= income Selection:if and if-else statements

  13. Boolean Expression Examples count + 1 > a * b far - near >= 10 Relational operators have lower precedence than arithmetic operators. The expressions are evaluated before the comparison. Invalid: a < b < c // syntax error a == b == c // syntax error Selection:if and if-else statements

  14. Indentation Helps Programmers but Java Ignores it. All simple statements within another statement should be indented further to the right than the outer statement. The two assignment statements are within the if. All statements in a sequence of statements in a compound statement should be indented the same amount, as the two assignment statements are. if (hours > 40) { over = hours - 40; pay = pay + over * (rate / 2); } Selection:if and if-else statements

  15. What Does This Program Do? import java.awt.*;import BreezyGUI.*;import java.math.*;public class Class extends GBFrame{IntegerField z = addIntegerField (0,1,1,2,1);Button publiC=addButton("Sure",3,2,1,1);DoubleField Z =addDoubleField(0,2,1,2,1);Button j=addButton("Yea, whatever",3,1 ,1,1);int button;double integerField;double g;int k;public void buttonClicked(Button buttonObj){button=z.getNumber();if(buttonObj ==j){integerField=Math.pow(0.5, button);;;Z.setNumber(integerField) ;}else if(buttonObj==publiC){integerField=(double)1/button;Z. setNumber(integerField);;}}public static void main(String[] args){Frame frm=new Class();frm.setSize( 300,200);frm.setVisible(true);}} A little hard to tell, isn’t it? Selection:if and if-else statements

  16. true balance > 0 display “Positive” false true balance < 0 display “Negative” false display “Zero” Multi-way Decisions Several possible paths: Selection:if and if-else statements

  17. Multi-way Decisions Assume outField is a TextField for display: if (balance > 0) outField.setText (“Positive”); else if (balance < 0) outField.setText (“Negative”); else outField.setText (“Zero”); Compound statements can be used here too. Selection:if and if-else statements

  18. Compute area from radius; Display area; area Compute area or radius? Compute radius from area; Display radius; radius yes radius > 0? Display error message; no Nested conditionals CircleAreaAndRadius (p. 76) Selection:if and if-else statements

  19. CircleAreaAndRadius -- Text p. 76. import java.awt.*; import BreezyGUI.*; public class CircleAreaAndRadius extends GBFrame { Label radiusLabel = addLabel ("Radius",1,1,1,1); DoubleField radiusField = addDoubleField (0,1,2,1,1); Label areaLabel = addLabel ("Area",2,1,1,1); DoubleField areaField = addDoubleField (0,2,2,1,1); Button radiusButton = addButton ("Compute Radius",3,1,1,1); Button areaButton = addButton ("Compute Area",3,2,1,1); double radius, area; Selection:if and if-else statements

  20. public void buttonClicked (Button buttonObj) { if (buttonObj == areaButton) { radius = radiusField.getNumber(); area = Math.PI * radius * radius; areaField.setNumber (area); } else { area = areaField.getNumber(); if (area >= 0) { radius = Math.sqrt (area / Math.PI); radiusField.setNumber (radius); } else messageBox ("Error: The area must not be\n" + "a negative number."); } } Selection:if and if-else statements

  21. public static void main (String[] args) { Frame frm = new CircleAreaAndRadius(); frm.setSize (200, 150); frm.setVisible (true); } } Selection:if and if-else statements

  22. CS 303E Lecture 7:Selection II (and a little design) You know you've achieved perfection in design, not when you have nothing more to add,but when you have nothing more to take away.-Antoine de Saint Exupery. Selection:if and if-else statements

  23. Designing a Program 1. Design interface: A Label and Field for each datum. One or more Buttons for computation. 2. Design computation: Get input. Compute result. Display result. (There are many more complex patterns.) Selection:if and if-else statements

  24. Step-Wise Refinement Or top-down implementation: • Start with a general outline. • Refine each piece by adding detail. • Refine each detail with more detail, as necessary. • Keep the pieces separate -- don’t mix them up. • Book mentions waterfall. Not used anymore!! Selection:if and if-else statements

  25. More on stepwise Refinement • Don’t follow the Analysis-Design-Implement-Integrate(Test) cycle blindly. • Better to • Design a little • Code a little • Test a little • Repeat • may not need to do this for small projects, but don’t get use to it. Selection:if and if-else statements

  26. Logical Operators -- && && (and): boolean_expression may be: boolean_expression && boolean_expression Truth Table for the boolean and operator p and q are both boolean expressions p q p && q false false false false true false true false false true true true Selection:if and if-else statements

  27. Logical Operators -- || || (or): boolean_expression may be: boolean_expression||boolean_expression Truth Table for the boolean and operator p and q are both boolean expressions p q p || q false false false false true true true false true true true true Selection:if and if-else statements

  28. Logical Operators -- ! ! (not): boolean_expression may be: !boolean_expression Truth Table for the boolean and operator p is a boolean expression. p !p false true true false Selection:if and if-else statements

  29. Type Boolean boolean b1, b2, b3; int i = 3, j = 4, k = 5; b1 = true; b2 = i < j; // value is true or false b3 = j <= k; private boolean isPrime (int number) { . . . return false; . . . return true; } Selection:if and if-else statements

  30. Type Boolean Used in loops and if statements to control computation. if (b1) outField.setText(“Yes!”); Used with logical operators: && (AND) || (OR) ! (NOT) Selection:if and if-else statements

  31. Boolean Variables Examples: boolean chk = a > 0 && (b <= 0 || c <= 0); boolean dataOk = false; . . . dataOk = name.equals(inputName) && id.equals(inputId) && numberField.isValid() && numberField.getNumber() > 0; . Selection:if and if-else statements

  32. A B A || B A && B true true true true true false true false false true true false false false false false A ! A true false false true Logical Operators Truth Tables Selection:if and if-else statements

  33. Evaluation exp1 || exp2 || . . . || expn Evaluate left to right, stop and return true when first exp is true; short circuit evaluation. if all are false, return false. exp1 && exp2 && . . . && expn Evaluate left to right, stop and return false when first exp is false; short circuit evaluation. if all are true, return true. . Selection:if and if-else statements

  34. Nested ifs and && if (cond1) if (cond2) . if (condn) statement; // Is equivalent to if (cond1 && cond2 && . . && condn) statement; The correct style depends on the situation. Sometimes nested if better, sometime compound boolean statement . Selection:if and if-else statements

  35. The switch Statement • Another way to do some multiway selection is via the switch statement: switch(expression) { case literal 1: group of statements; break; case literal 2: group of statements; break; … case literal n: group of statements; break; default: group of statements; break; } Selection:if and if-else statements

  36. The switch Statement • Can be used in some cases as an alternative to multiple if - else if - else statements. • Limited in its usefulness • the controlling expresion must evaluate to an integer or a character, (another primitive data type.) • The cases must be constant expressions. They may only be constants or literals. • Missing break evaluation continues looking for a match Selection:if and if-else statements

  37. The Assignment that Could Have Been Request: Write a program to allow a user to play rock-paper-scissors against the computer. Keep a track of how many games each player wins and the number of ties Okay, Go. Selection:if and if-else statements

  38. Analysis • Questions for the requestor? Selection:if and if-else statements

  39. Design • GUI • Program Selection:if and if-else statements

  40. Implementation public void buttonClicked(Button buttonObj) { Selection:if and if-else statements

More Related