Download presentation
Presentation is loading. Please wait.
Published byLenard Gallagher Modified over 9 years ago
1
ITP © Ron Poet Lecture 5 1 Branching
2
ITP © Ron Poet Lecture 5 2 CookTime After Midnight We want to improve our program so that we can cook meals after midnight. We detect the problem when we get a negative startTotalMins. Easy to fix, just add total number of minutes in a day if startTotalMins is negative. There are 24 * 60 = 1440 minutes in a day. Assume cooking time is less than 24 hours!
3
ITP © Ron Poet Lecture 5 3 Tests In Programs We can test values in our programs. The program will take two different branches. Depending on the actual values tested when the program runs. startTotalMins can be positive most time, but occasionally negative. If it is negative then we add 1440 and carry on.
4
ITP © Ron Poet Lecture 5 4 Simple Branch The simplest form of branching structure is to do some additional work if a test is true. Then carry on with the main scenario. Test Carry On Additional Work true false
5
ITP © Ron Poet Lecture 5 5 Refine Sequence of Activities We take the simple activity: Calculate cooking time. and provide more details. Calculate cookTime. Calculate end time in total minutes Calculate start time in total minutes if start time is negative add 1440 to start time Calculate start hours and minutes.
6
ITP © Ron Poet Lecture 5 6 Simple Branch in Java Java uses the word if for a simple branch. if (test is true) statement The statement can also be a compound statement if we wanted to do several things before returning to the main path. If the test is false then the statement is not done.
7
ITP © Ron Poet Lecture 5 7 Numerical Tests There are 6 possible tests involving numerical values. The answer is either true or false. x == y true if x equals y x != y true if x does not equal y x > y true if x is bigger than y x >= y true if x is bigger than or equal to y x < y true if x is less than y x <= y true if x is less than or equal to y
8
ITP © Ron Poet Lecture 5 8 Modifying the start time We want a test that is true if the start time is negative. Use a numerical test with <. if (startTotalMins < 0) startTotalMins = startTotalMins + 1440;
9
ITP © Ron Poet Lecture 5 9 New calculate cook time int cookTime = (int) (minsPerKg * weight + extraMins); int endHours = time / 100; int endMins = time % 100; int endTotalMins = 60 * endHours + endMins; int startTotalMins = endTotalMins - cookTime; if (startTotalMins < 0) startTotalMins = startTotalMins + 1440; int startHours = startTotalMins / 60; int startMins = startTotalMins % 60;
10
ITP © Ron Poet Lecture 5 10 Indentation Note how the inside of the if is indented. That makes it easier to follow the structure of the branch. The code inside the if is only executed if the test is true. The code before and after the if is always executed.
11
ITP © Ron Poet Lecture 5 11 Two Things Inside the if Let us print a message on System.err as well as add 1440 if startTotalMins < 0. The 'inside' of the if is a single statement Which can be a compound statement. if (startTotalMins < 0) { startTotalMins = startTotalMins + 1440; System.err.println("Midnight Feast!"); }
12
ITP © Ron Poet Lecture 5 12 Indentation Can Be Deceiving Let us accidentally 'forget' the {}. if (startTotalMins < 0) startTotalMins = startTotalMins + 1440; System.err.println("Midnight Feast!"); The print statement is not inside the if. It will always print "Midnight Feast" even for meals during the day. Only the first statement is inside the if. The indentation has mislead us.
13
ITP © Ron Poet Lecture 5 13 Are Two Strings Equal? Beware! Do not compare Strings with ==. String a = "Fred", b = "Fred"; if (a == b)... is legal Java but does not do what you think! In this case the test is false!
14
ITP © Ron Poet Lecture 5 14 Proper Equality Test For Strings If a and b are Strings then the equality test is a.equals(b). This is clumsy, but we must use it. if (a.equals(b))... A test that is true if the Strings are not equal is even worse! if (!a.equals(b))...
15
ITP © Ron Poet Lecture 5 15 An Example With Strings The following silly example asks the user to type their name. If their name is "Ron" they get a special welcome before the general message. con.print("Who are you: "); String name = con.readWord(); if (name.equals("Ron")) con.println("Why, Hello Ron"); con.println("Now lets get down to work.");
16
ITP © Ron Poet Lecture 5 16 Alternate Paths This is a more complicated branch. We do one alternative or another before returning to the main path. Test Activity 1 Activity 2 Carry On true false
17
ITP © Ron Poet Lecture 5 17 One Or The Other We either do Activity 1 or Activity 2 but not both. Both branches join up to Carry On. It s easy to see in our two dimensional diagram. But harder to express as a linear sequence.
18
ITP © Ron Poet Lecture 5 18 The else Part of the if In Java we write the part to do if the test is true as before. Then write the word else and the part to do if the test is false. if (Test) statement_if_true; else statement_if_false; Naturally we can use compound statements in each part.
19
ITP © Ron Poet Lecture 5 19 Example We add a greeting if the person is not Ron. con.print("Who are you: "); String name = con.readWord(); if (name.equals("Ron")) con.println("Why, Hello Ron"); else con.println("I don\'t think we have met"); con.println("Now let\'s get down to work.");
20
ITP © Ron Poet Lecture 5 20 Calculating the Maximum The following code assigns the maximum value of two variables a, b to max. We must define max before the if because of scope. con.print("Type two integers: "); int a = con.readInt(); int b = con.readInt(); int max; if (a > b) max = a; else max = b;
21
ITP © Ron Poet Lecture 5 21 Chaining if Statements We often want to make a series of tests on the same value one after the other. The statement in the else part can be another if statement. We must make sure we do the tests in the correct order! The following example prints a message based on the strength of an earthquake. Note the layout and indentation convention.
22
ITP © Ron Poet Lecture 5 22 Richter Scale // start with double richter == strength of earthquake if (richter >= 8.0) con.println("Most structures fall"); else if (richter >= 7.0) con.println("Many buildings destroyed"); else if (richter >= 6.0) con.println("Some buildings collapse"); else if (richter >= 4.5) con.println("Damage to poorly built buildings"); else if (richter >= 3.5) con.println("Felt but no destruction"; else con.println("Not noticed";
23
ITP © Ron Poet Lecture 5 23 Chaining Explained Note that we must stop eventually. There is a final else without another if. Note that the first test only catches the very big earthquakes. The tests are progressively easier. What would happen if the first test caught them all? The next example shows what happens if we omit the else words. An earthquake of strength 6.3 would print 3 messages.
24
ITP © Ron Poet Lecture 5 24 Richter Scale, but WRONG // start with double richter == strength of earthquake if (richter >= 8.0) con.println("Most structures fall"); if (richter >= 7.0) con.println("Many buildings destroyed"); if (richter >= 6.0) con.println("Some buildings collapse"); if (richter >= 4.5) con.println("Damage to poorly built buildings"); if (richter >= 3.5) con.println("Felt but no destruction"; else con.println("Not noticed";
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.