Presentation is loading. Please wait.

Presentation is loading. Please wait.

CONDITIONALS CITS1001. Scope of this lecture if statements switch statements Source ppts: Objects First with Java - A Practical Introduction using BlueJ,

Similar presentations


Presentation on theme: "CONDITIONALS CITS1001. Scope of this lecture if statements switch statements Source ppts: Objects First with Java - A Practical Introduction using BlueJ,"— Presentation transcript:

1 CONDITIONALS CITS1001

2 Scope of this lecture if statements switch statements Source ppts: Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling; and Gordon Royle, UWA 2

3 Dynamic behaviour One of the main reasons for the widespread usefulness of computers is their ability to behave dynamically The same hardware can perform many different tasks In programs, dynamic behaviour is specified by the use of control structures which can vary the order in which statements are executed The two fundamental ideas are selection and repetition Selection: the ability to decide which (or whether) statement-blocks are performed by examining run-time data values Repetition: the ability to perform statement-blocks multiple times, determining the number of repeats by examining run-time data values 3

4 Making choices in everyday life If I have enough money left, I will go out for a meal Otherwise, I will stay home and watch a movie if(I have enough money left) { // go out for a meal; } else { // stay home and watch a movie; } The result depends on the amount of money available at the time the decision is made 4

5 Making choices in Java if(perform some test) { Do these statements if the test gave a true result } else { Do these statements if the test gave a false result } ‘if’ keyword boolean condition to be tested actions to perform if condition is true actions to perform if condition is false ‘else’ keyword 5

6 Execution When the conditional statement is encountered, the Boolean expression is evaluated It returns either true or false If the result is true, the first statement block is executed, and the second is skipped If the result is false, the first statement block is skipped, and the second is executed In every case, exactly one of the blocks is executed In every case, execution continues with the statements following the conditional (if any) 6

7 Flow of execution if(condition) { } else { } The order of execution here is, then either or, then 7

8 Omitting the else -block Sometimes we just want to say “if this condition is true, execute these statements; if not, do nothing” Just omit the else –block e.g. if(perform some test) { Do these statements if the test gave a true result } if(balance < 0) { System.out.println(“Give us our money back!”); } 8

9 Repeating the conditional Sometimes there are more than two possible choices Just repeat (or nest) the conditionals But still only one block is executed if(perform test1) { Do these statements if test1 gave a true result } else if (perform test2) { Do these statements if test1 gave a false result and test2 gave a true result } else { Do these statements if both tests gave a false result } 9

10 Or more… Sometimes there are many possible choices! No problem… but it can get a bit verbose if(perform test1) { Do these statements if test1 gave a true result } else if (perform test2) { Do these statements if test1 false and test2 true } else if (perform test3) { Do these statements if tests 1-2 false and test3 true } else if (perform test4) { Do these statements if tests 1-3 false and test4 true } else { Do these statements if all tests gave a false result } 10

11 An example – guess the number In a classic children’s game, Bob chooses a number in the range 1–100, and June repeatedly tries to guess it Each of June’s guesses gets a response from Bob Either “too high”, or “too low”, or “well done!” How would we write a Java class to play this game? The computer will be Bob Each object in this class plays one game, thus it needs to choose a number randomly and then respond to each of the player’s guesses We need to specify the class’s instance variable(s), its constructor(s), and its method(s) 11

12 Instance variables We need only one instance variable, to store the chosen number public class GuessTheNumber { private int secretNumber; } 12

13 Constructors The constructor needs to choose the number i.e. it needs to initialise the instance variable But how do we choose a random number? Using a library class import java.util.Random; public GuessTheNumber() { Random r; r = new Random(); secretNumber = r.nextInt(100) + 1; } Declares a new variable r to hold a random number generator Asks r for a random int between 0 and 99, and then adds 1 to get a number between 1 and 100 Allows us to use the “short name” Random Creates a new RNG and assigns it to r 13

14 Random numbers The constructor is simple enough and there’s the method we need 14

15 Methods We need only one method, to respond to a guess public String checkMyGuess (int guess) { String response; if (guess > secretNumber) { response = “too high”; } else if (guess < secretNumber) { response = “too low”; } else { response = “well done!”; } return response; } A local variable in the method A parameter to the method The object’s instance variable 15

16 Or… public String checkMyGuess (int guess) { String response = “well done!”; if (guess > secretNumber) { response = “too high”; } else if (guess < secretNumber) { response = “too low”; } return response; } Pre-initialise the return variable 16

17 Or… public String checkMyGuess (int guess) { String response = “well done!”; if (guess > secretNumber) { response = “too high”; } if (guess < secretNumber) { response = “too low”; } return response; } Pre-initialise, and don’t nest the conditionals 17

18 Or… public String checkMyGuess (int guess) { String response = “well done!”; if (guess > secretNumber) response = “too high”; if (guess < secretNumber) response = “too low”; return response; } Pre-initialise, don’t nest, and save the {} 18

19 Or… public String checkMyGuess (int guess) { if (guess > secretNumber) return “too high”; else if (guess < secretNumber) return “too low”; else return “well done!”; } The method terminates as soon as it executes any return statement Don’t use a return variable, with nesting 19

20 Or… public String checkMyGuess (int guess) { if (guess > secretNumber) return “too high”; if (guess < secretNumber) return “too low”; return “well done!”; } No return variable, no nesting, and save the last check 20

21 But NOT public String checkMyGuess (int guess) { if (guess > secretNumber) return “too high”; if (guess < secretNumber) return “too low”; if (guess == secretNumber) return “well done!”; } Java is being too careful – it can’t guarantee a return! No return variable, no nesting, and all three checks 21

22 An enhancement Suppose we want the class to count (and report) the number of guesses taken to find the number What do we need to do? We need an instance variable numGuesses to record the number of guesses so far The constructor needs to initialise numGuesses The method needs to update numGuesses as appropriate The method needs to print an appropriate message when the game is over Try this in the lab next week 22

23 The switch statement Sometimes we want to choose what to do based on several possible values that a number can have public String classify (int mark) { String grade; if (mark >= 80) grade = “HD”; else if (mark >= 70) grade = “D”; else if (mark >= 60) grade = “CR”; else if (mark >= 50) grade = “P”; else grade = “N”; return grade; } 23

24 The switch statement That code is tedious both to write and to read! public String classify (int mark) { String grade; switch (mark / 10) { case 9: grade = “HD”; break; case 8: grade = “HD”; break; case 7: grade = “D”; break; case 6: grade = “CR”; break; case 5: grade = “P”; break; default: grade = “N”; } return grade; } 24

25 The switch statement The statement evaluates the int expression once If the result matches any of the explicit cases listed, execution resumes at that point If it matches none of the explicit cases listed, execution resumes at the default case Although the default case is optional A break statement causes execution to jump to the statements following the entire switch statement If there is no break, execution just continues over multiple cases 25


Download ppt "CONDITIONALS CITS1001. Scope of this lecture if statements switch statements Source ppts: Objects First with Java - A Practical Introduction using BlueJ,"

Similar presentations


Ads by Google