Presentation is loading. Please wait.

Presentation is loading. Please wait.

Flow of Control Branching

Similar presentations


Presentation on theme: "Flow of Control Branching"— Presentation transcript:

1 Flow of Control Branching
Chapter 3 Ch 1 – Introduction to Computers and Java Flow of Control Branching

2 Chapter 3 3.1 The if-else Statement 3.2 The Type boolean
3.3 The switch Statement 3.4 Graphics Supplement

3 3.1 The if-else Statement

4 Flow Chart Deconstructed
Terminator: Show start/stop points boolean expression true statements false statement Start Stop Decision: Make a choice T F Process: Statements to execute A flow chart is an easy way to graphically express your logic, without having to write any code. You are encouraged to develop your flowcharting skills as a means to express your solution graphically. As a programmer you are constantly asked to solve problems, and using algorithms is how you present your step by step solution to the problem at hand, that does not require the use of code. So, an algorithm, being your recipe of steps to follow in order to solve a particular problem can be graphically represented with a flowchart. It is another way to show the same results, one text base and the other graphical based. Connector: Connect lines

5 Flow Chart Deconstructed <Taxes owed>
Start income <= NO_TAX_AMOUNT taxesOwed = 0.0 T taxesOwed = income * TAX_RATE F In the example demonstrated above, we begin with the "Start" terminator as the beginning of our algorithm. We then have to make a choice, is the income less than or equal to the no tax amount? This choice is shown with the use of the "Decision" symbol, and as shown, it has two possible outcomes, True or False. If the income is less than or equal to the no tax amount, we execute the statement(s) on the left, i.e. we assign 0.0 to the variable taxesOwed. If the income is greater, we execute the statement(s) on the right, which assigns the quantity income * TAX_RATE to the income variable. As you can see from above, one of two outcomes is possible. We say that the choices are mutually exclusive, only one of the two will ever execute after a decision has been made. Once a decision has been made and one of the two outcomes is executed, then execution continues with the steps that follow. This is indicated with the conversion of the flow lines into the "Connector" and ultimately the "Stop" terminator. Stop

6 If else Deconstructed <Taxes owed>
boolean expression ... if (income <= NO_TAX_AMOUNT) { taxesOwed = 0.0; } else { taxesOwed = income * TAX_RATE; } //end if true statements false statements Java provides the if control structure for making decisions. The above example shows a decision with two possible outcomes, thus an if-else is used. The statements after the if boolean expression make up the true block, and the statements after the else make up the false block. Keep in mind that the else part is always optional and its use depends on how many possible outcomes you have. If you have one, then it is not used, if two it is used.

7 Application Deconstructed <TaxesOwed.java>
package taxesowed; import java.util.Scanner; public class TaxesOwed { public static final double NO_TAX_AMOUNT = ; public static final double TAX_RATE = 0.03; public static void main(String[] args) { double income; double taxesOwed; Scanner keyboard = new Scanner(System.in); System.out.print("Enter your income amount: $"); income = keyboard.nextDouble();

8 Application Deconstructed <TaxesOwed.java>
if (income <= NO_TAX_AMOUNT) { taxesOwed = 0.0; } else { taxesOwed = income * TAX_RATE; }// end else System.out.println("You owe $" + taxesOwed + " on an income of $" + income); }// end main() }// end TaxesOwed

9 Boolean expressions may use the following relational operators
Operation Operator Example equality == a == b inequality != a != b greater than > a > b greater than or equal >= a >= b less than < a < b less than or equal <= a <= b The relational operators or comparison operators allow you to perform a number of comparisons whose outcome is a boolean result, i.e. either true or false. Warning: The equality is expressed with two equal signs, not one, so be careful as the latter will cause an error. For example, if (a = b) is not the same as if (a == b), and will make the compiler very unhappy. The equality works as expected with integral values, but not so well with floating point and strings. Floating point variables recall, may be simply approximations of the actual numbers, thus comparison may lead to undesirable results. It is best to compare the difference of the two against an acceptable margin of error. Strings also pose a problem, since strings are actually objects. An object variable is nothing more than a reference (pointer) to the actual value of the object in memory, and thus two separate memory locations could have the exact same string value, but since their memory locations are different, the relational operators will result in an inaccurate outcome. An example of this is shown next.

10 ... and the following logical operators
Operation Operator Example And && (a < b) && (c > d) Or || (a == b) || (c == d) Not ! !fileIsOpen Logical operators can be used to create compound expressions. The meaning of the operators is similar to what you may have learned while studying boolean algebra. Here is the low down on each one. && : True only when both arguments are true, false otherwise. || : False only when both argumenst are false, true otherwise. ! : The complement of its argument. This one should be avoided in expressions using the relational operators, since it leads to unreadable code. For example, !(c < 0) is best expressed as (c >= 0), a more readable form.

11 Application Deconstructed <StringEquality.java>
package stringequality; import java.util.Scanner; public class StringEquality { public static void main(String[] args) { String str1; String str2; Scanner keyboard = new Scanner(System.in); System.out.print("Enter some text: "); str1 = keyboard.nextLine(); System.out.print("Enter more text: "); str2 = keyboard.nextLine();

12 Application Deconstructed <StringEquality.java>
System.out.println(); System.out.println("str1 = \"" + str "\" : str2 = \"" + str2 + "\""); System.out.println("str1 == str2 ? " + (str1 == str2)); System.out.println("str1.equals(str2) ? " str1.equals(str2)); System.out.println("str2.equals(str1) ? " str2.equals(str1)); == asks: are they the same object? The others compare the text. Notice how the test str1 == str2 evaluates to false, even though the two string objects have the same value. This is important to understand because it underlies the fact that object variables (str1, str2 in this example) are merely references (pointers) to the actual objects, which both happen to the have the same value ("Apples are red"), but are in different memory locations. For proper string value comparisons, use the method .equals().

13 Application Deconstructed <StringEquality.java>
str2 = "apples are red"; System.out.println(); System.out.println("str1 = \"" + str "\" : str2 = \"" + str2 + "\""); System.out.println("str1.equals(str2) ? " str1.equals(str2)); System.out.println("str1.equalsIgnoreCase(str2) ? " str1.equalsIgnoreCase(str2)); }// end main() }// end StringEquality Since Java is case sensitive, if you want to compare two strings without accounting for the case, then use the method .equalsIgnoreCase(), as shown above. This method treats uppercase the same as lowercase.

14 Application Deconstructed <StringEquality.java>

15 Application Deconstructed <MultiBranchIf.java>
package multibranchif; import java.util.Scanner; public class MultiBranchIf { public static final int SUN = 1; public static final int MON = 2; public static final int TUE = 3; public static final int WED = 4; public static final int THU = 5; public static final int FRI = 6; public static final int SAT = 7; public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); int weekDayNumber; String weekDayName = ""; constants for the days of the week Notice the use of constants to aid readability and maintenance. If a change is needed later on to one of these values, then all you have to do is change one constant value. You will not have to search all of your code for each occurrence of the value itself.

16 Application Deconstructed <MultiBranchIf.java>
System.out.print("Enter the day of the week [1-Sunday...7-Saturday]: "); weekDayNumber = keyboard.nextInt(); if (weekDayNumber == SUN) { weekDayName = "Sunday"; }else if (weekDayNumber == MON) { weekDayName = "Monday"; }else if (weekDayNumber == TUE) { weekDayName = "Tuesday"; }else if (weekDayNumber == WED) { weekDayName = "Wednesday"; }else if (weekDayNumber == THU) { weekDayName = "Thursday"; }else if (weekDayNumber == FRI) { weekDayName = "Friday"; }else if (weekDayNumber == SAT) { weekDayName = "Saturday"; }// end if This is just an if else, where each else contains an if else. Recall that this if-else if structure is an if-else with nested if's inside the else. For instance, if (...) { ... }else if (...) { } else { can be rewritten as: } else {

17 Application Deconstructed <MultiBranchIf.java>
System.out.println("I see you chose " + weekDayName + "."); }// end main() }// end MultiBranchIf

18 The conditional operator is very handy
// The following if-else: if (minute == 60) { minute = 0; } else { minute += 1; // can be written with a conditional operator as: minute = (minute == 60)? 0 : minute + 1; The conditional operator is just like an if-else. An expression is given in parentheses followed by a question mark; this constitues your boolean expression in an if. If the expression evaluates to true then the first part between the ? and the : is executed. This is the equivalent of the true block in an if. Next comes the part between the : and the ;. This is the equivalent of the false block in an if.

19 Recap Use flowcharts to express algorithms. Use the if for decisions.
Use .equals or .equalsIgnoreCase with strings

20 3.2 The Type boolean True or False?

21 Boolean expressions evaluate to true or false
number > 0 True if number > 0, false otherwise 3 > 4 False 3 True, since not 0 Every boolean expression must evaluate to either true or false. Zero means false, and any non zero value means true.

22 Boolean variables simplify
// Testing for leap year. if ( (year % 100 != 0) && (year % 4 == 0) || (year % 400 == 0) ) { // leap year } The && has higher priority than || // Testing for leap year. boolean isLeap = (year % 100 != 0) && (year % 4 == 0) || (year % 400 == 0); if (isLeap) { // leap year } The second "if" is a lot easier to read and thus should be preferred over the first example, which is a lot hard to read and debug. A boolean variable can receive the evaluation of a boolean expression, as in: boolean isOfAge = (age > 21); The variable isOfAge will be true if age > 21, false otherwise.

23 Be mindful of the order of evaluation
Parentheses go first, then Arithmetic, then Relational, and then Logical

24 Brainteaser time! int x = 3 * 5 + (4 – 5) / 2 + 6 % 4;
bool goAhead = 5 > 3 || < 3 * 2; bool isRaining = true; bool haveUmbrella = false; bool gotWet = isRaining && !haveUmbrella;

25 Booleans use true or false
boolean isOld = true; System.out.println("isOld = " + isOld); // displays isOld = true System.out.print("Answer true or false. This is fun: "; boolean isOfAge = keyboard.nextBoolean(); // IO Answer true of false. This is fun: true

26 Recap Booleans hold either true or false.
(), arithmetic, relational, logical, in that order. Boolean variables simplify code.

27 3.3 The switch statement statements True False case 1 default case n

28 Switch Deconstructed switch (expression) { case label1: statements;
[break]; case label2: statements; ... default: statements; } break is optional sdk 7: label can be a string default is optional

29 Switch Deconstructed <DayOfTheWeek>
// ... code omitted switch (dayOfTheWeek) { case MON: case TUE: case WED: case THU: case FRI: System.out.println("Bah, still a work day!"); break; case SAT: case SUN: System.out.println("Woo hoo, weekend!); break; default: System.out.println("No comprendo!"); break; } Evaluation will begin at the top of the switch, and as soon as one case is selected, its body will execute and the switch will exit. If none of the cases are selected, then the default case will execute. If the break is omitted from any case then after its body is executed, control will always continue with the next case that follows.

30 Brainteaser time! Draw the flow chart for the DayOfTheWeek switch

31 Application Deconstructed <DayOfTheWeek.java>
package dayoftheweek; import java.util.Scanner; public class DayOfTheWeek { public static final int SUN = 1; public static final int MON = 2; public static final int TUE = 3; public static final int WED = 4; public static final int THU = 5; public static final int FRI = 6; public static final int SAT = 7; public static void main(String[] args) { int dayOfTheWeek; Scanner keyboard = new Scanner(System.in);

32 Application Deconstructed <DayOfTheWeek.java>
System.out.print("Enter the day of the week [Sun = 1...Sat = 7]: "); dayOfTheWeek = keyboard.nextInt(); switch (dayOfTheWeek) { case MON: case TUE: case WED: case THU: case FRI: System.out.println("Bah, still a work day!"); break; case SAT: case SUN: System.out.println("Woo hoo, weekend!"); default: System.out.println("No comprendo!"); }// end switch }// end main() }// end DayOfTheWeek

33 3.4 Graphics Supplement

34 Applet Deconstructed < YellowSmileyFace.java >
package yellowsmileyface; import javax.swing.JApplet; import java.awt.Color; import java.awt.Graphics; public class YellowSmileyFace extends JApplet { public static final int FACE_DIAMETER = 200; public static final int X_FACE = 100; public static final int Y_FACE = 50; public static final int EYE_WIDTH = 10; public static final int EYE_HEIGHT = 20; public static final int X_RIGHT_EYE = 155; public static final int X_LEFT_EYE = 230; public static final int Y_RIGHT_EYE = 100; public static final int Y_LEFT_EYE = Y_RIGHT_EYE; public static final int NOSE_DIAMETER = 10; public static final int X_NOSE = 195; public static final int Y_NOSE = 135; To write an applet, make sure you import the JApplet class. To draw graphics, you must import the Graphics class as shown above. You will need to also chage the first line of the class declaration by adding "extends JApplet", which tells the compiler that you are going to be creating an applet rather than an application.

35 Applet Deconstructed < YellowSmileyFace.java >
public static final int MOUTH_WIDTH = 100; public static final int MOUTH_HEIGHT = 50; public static final int X_MOUTH = 150; public static final int Y_MOUTH = 160; public static final int MOUTH_START_ANGLE = 180; public static final int MOUTH_EXTENT_ANGLE = 180; @Override public void paint(Graphics canvas) { canvas.setColor(Color.YELLOW); canvas.drawOval(X_FACE, Y_FACE, FACE_DIAMETER, FACE_DIAMETER); Next, you will have to remove the main() method, since we are creating an applet. In its stead, add the paint method as shown above. This is the entry point for applets, just like main() is the entry point for applications. directive simply states that we are overriding the paint method that is provided by the language. Overriding basically means, use my version, not yours. canvas.setColor(Color.BLACK); canvas.drawOval(X_FACE, Y_FACE, FACE_DIAMETER, FACE_DIAMETER);

36 Applet Deconstructed < YellowSmileyFace.java >
canvas.setColor(Color.BLUE); canvas.fillOval(X_RIGHT_EYE, Y_RIGHT_EYE, EYE_WIDTH, EYE_HEIGHT); canvas.fillOval(X_LEFT_EYE, Y_LEFT_EYE, EYE_WIDTH, EYE_HEIGHT); canvas.setColor(Color.BLACK); canvas.fillOval(X_NOSE, Y_NOSE, NOSE_DIAMETER, NOSE_DIAMETER); canvas.setColor(Color.RED); canvas.drawArc(X_MOUTH, Y_MOUTH, MOUTH_WIDTH, MOUTH_HEIGHT, MOUTH_START_ANGLE, MOUTH_EXTENT_ANGLE); }// end paint() }// end HappyFaceAppletConstants

37 Applet Deconstructed < YellowSmileyFace.java >
To execute the applet in the applet viewer, chose Run | Run File, sit back and enjoy.

38 Application Deconstructed < NameThatCountry.java >
package namethatcountry; import javax.swing.JFrame; import java.awt.Color; import java.awt.Graphics; import javax.swing.JOptionPane; public class NameThatCountry extends JFrame { public static final int FRAME_WIDTH = 600; public static final int FRAME_HEIGHT = 400; public static final int BAND_WIDTH = 120; public static final int BAND_HEIGHT = 250; public static final int X_FLAG = (FRAME_WIDTH - 3 * BAND_WIDTH) / 2; public static final int Y_FLAG = (FRAME_HEIGHT - BAND_HEIGHT) / 2; public static final int X_GREEN = X_FLAG; public static final int Y_GREEN = Y_FLAG;

39 Application Deconstructed < NameThatCountry.java >
public static final int X_WHITE = X_GREEN + BAND_WIDTH + 1; public static final int Y_WHITE = Y_FLAG; public static final int X_ORANGE = X_WHITE + BAND_WIDTH + 1; public static final int Y_ORANGE = Y_FLAG; public static void main(String[] args) { NameThatCountry flagWindow = new NameThatCountry(); flagWindow.setVisible(true); String countryName = JOptionPane.showInputDialog("Can you name this country?"); if ( countryName.equalsIgnoreCase("Ireland") ) { JOptionPane.showMessageDialog(null, "Nice Job."); } else { JOptionPane.showMessageDialog(null, "Sorry, its Ireland"); }// end else System.exit(0); }// end main() main first starts off by creating a new instance of the NameThatCountry class. This statement causes the method NameThatCountry() to execute. During the construction of the window the paint() method is called to draw or paint all of the UI elements as indicated in the paint() method itself. All of this is done in the background, which is more a more efficient way to create graphics. The alternative is to draw directly to the screen, which often causes a flicker. Once the flagWindow is made visible, the user sees the UI and is able to interact with it. In this example an input dialog box will ask the user for their guess. After providing a guess and checked against the correct answer, a message dialog box will inform the user if their guess was right or wrong.

40 Application Deconstructed < NameThatCountry.java >
public NameThatCountry() { setSize(FRAME_WIDTH, FRAME_HEIGHT); setTitle("Name that country"); }// end NameThatCountry() @Override public void paint(Graphics canvas) { canvas.setColor(Color.GREEN); canvas.fillRect(X_GREEN, Y_GREEN, BAND_WIDTH, BAND_HEIGHT); canvas.setColor(Color.WHITE); canvas.fillRect(X_WHITE, Y_WHITE, BAND_WIDTH, BAND_HEIGHT); canvas.setColor(Color.ORANGE); canvas.fillRect(X_ORANGE, Y_ORANGE, BAND_WIDTH, BAND_HEIGHT); } }// end NameThatCountry

41 Application Deconstructed < NameThatCountry.java >

42 Application Deconstructed < NameThatCountry.java >


Download ppt "Flow of Control Branching"

Similar presentations


Ads by Google