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

Slides:



Advertisements
Similar presentations
Flow of Control Chapter 3.
Advertisements

Understanding class definitions Looking inside classes 5.0.
CS0007: Introduction to Computer Programming
Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
Selection Statements choice of one among several blocks of code Java supports 3 kinds of selection statements: if statement – selects one block or leaves.
Aalborg Media Lab 23-Jun-15 Software Design Lecture 6 “Conditionals and Loops”
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Grouping Objects 2 Collections and the for-each loop Collections and the while loop.
Understanding class definitions – Part II –. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main.
1 Reflecting on the ticket machines Their behavior is inadequate in several ways: –No checks on the amounts entered. –No refunds. –No checks for a sensible.
Programming with Collections Grouping & Looping - Collections and Iteration Week 7.
Understanding class definitions Looking inside classes.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 30, 2005.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
The switch Statement, DecimalFormat, and Introduction to Looping
Games and Simulations O-O Programming in Java The Walker School
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
Programming Fundamentals. Today’s lecture Decisions If else …… Switch Conditional Operators Logical Operators.
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
5-1 Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements,
Flow of Control Part 1: Selection
Conditions. Objectives  Understanding what altering the flow of control does on programs and being able to apply thee to design code  Look at why indentation.
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Grouping objects Introduction to collections 5.0.
Making Decisions uCode: October Review What are the differences between: o BlueJ o Java Computer objects represent some thing or idea in the real.
Grouping objects Collections and iterators Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main.
Current Assignments Homework 2 is available and is due in three days (June 19th). Project 1 due in 6 days (June 23 rd ) Write a binomial root solver using.
1 Week 6 Branching. 2 What is “Flow of Control”? l Flow of Control is the execution order of instructions in a program l All programs can be written with.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 5: Introduction to C: More Control Flow.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 ‏ Control Structures.
4.1 Object Operations operators Dot (. ) and new operate on objects The assignment operator ( = ) Arithmetic operators + - * / % Unary operators.
Understanding class definitions
1 COS 260 DAY 3 Tony Gauvin. 2 Agenda Questions? 1 st Mini quiz on chap1 terms and concepts –Today In BlackBoard –30 min., M/C and short answer, open.
CMP-MX21: Lecture 5 Repetitions Steve Hordley. Overview 1. Repetition using the do-while construct 2. Repetition using the while construct 3. Repetition.
Conditional Statements Consider: if the mouse location is contained in the rectangle, display message “success” Some programming constructs can choose.
Java Decision Making and booleans (Java: An Eventful Approach, Ch 4), Slides Credit: Bruce, Danyluk and Murtagh CS 120 Lecture October 2012.
ICT Introduction to Programming Chapter 4 – Control Structures I.
Java Programming Fifth Edition Chapter 5 Making Decisions.
Chapter 5: Making Decisions. Objectives Plan decision-making logic Make decisions with the if and if…else structures Use multiple statements in if and.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
COMP Loop Statements Yi Hong May 21, 2015.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
CS0007: Introduction to Computer Programming The for Loop, Accumulator Variables, Seninel Values, and The Random Class.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Understanding class definitions Exploring source code 6.0.
Chapter 7 Control Structures. Java has very flexible three looping mechanisms. You can use one of the following three loops:  while Loop  do...while.
Conditional Statements A conditional statement lets us choose which statement will be executed next Conditional statements give us the power to make basic.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
 By the end of this section you should be able to: ◦ Differentiate between sequence, selection, and repetition structure. ◦ Differentiae between single,
CS100Lecture 61 Announcements Homework P1 due on Thursday Homework P2 handed out.
Information and Computer Sciences University of Hawaii, Manoa
Branching statements.
Core Java Statements in Java.
Class definitions CITS1001 week 2.
Lecture 3- Decision Structures
Review If you want to display a floating-point number in a particular format use The DecimalFormat Class printf A loop is… a control structure that causes.
Control Structures.
Understanding class definitions
Understanding class definitions
COS 260 DAY 3 Tony Gauvin.
CS139 October 11, 2004.
Understanding class definitions
COS 260 DAY 4 Tony Gauvin.
Comparing Data & the ‘switch’ Statement
Comparing Data & the ‘switch’ Statement
Presentation transcript:

CONDITIONALS CITS1001

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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