Top Banner
Chapter 4 Control Structures Foundational Java Key Elements and Practical Programming 1 Foundational Java by David Parsons © 2012
29

Chapter 4 Control Structures - foundjava.com

Feb 20, 2022

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Chapter 4 Control Structures - foundjava.com

Chapter 4 Control Structures

Foundational Java Key Elements and Practical Programming

1 Foundational Java by David Parsons © 2012

Page 2: Chapter 4 Control Structures - foundjava.com

Control Structures

• if-else

• switch

– break and continue

• Ternary operator

• ‘while’ and ‘do-while’ loops

• ‘for’ loops

• no goto !

2 Foundational Java by David Parsons © 2012

Page 3: Chapter 4 Control Structures - foundjava.com

Making Selections

• Two forms

– if

– if-else

• The if keyword is always followed by parentheses

– The expression in the parentheses must evaluate to a boolean

• The statement can be a single statement or a block

– Safer as a block

3

if (booleanExpression) statement;

if (booleanExpression) { statement(s); }

Foundational Java by David Parsons © 2012

Page 4: Chapter 4 Control Structures - foundjava.com

If…else Statements

• The ‘else’ part is optional

• If the condition is false and there is no ‘else’ part then no code in the conditional statement will be executed

4

if(condition) { // do this } else { // do this instead }

Foundational Java by David Parsons © 2012

Page 5: Chapter 4 Control Structures - foundjava.com

Nested Statements

• Use braces for each block

5

if(condition)

{

// statements

}

else

{

if(condition)

{

// statements

}

else

{

// statements

}

}

Foundational Java by David Parsons © 2012

Page 6: Chapter 4 Control Structures - foundjava.com

Comparison Operators

• Used to create Boolean expressions (return true or false)

• The relational operators: < Less than

> Greater than

<= Less than or equal to

>= Greater than or equal to

– Can only be used with numeric primitives

• The equality operators: == Equal

!= Not equal

– Can be used with all data types

– A common error in Java is to confuse the = and == operators

6 Foundational Java by David Parsons © 2012

Page 7: Chapter 4 Control Structures - foundjava.com

Examples

7

Condition

Operator Example

equal to

==

if(temperature == 100)

not equal to

!= if(grade != 'F')

less than

< if(sales < target)

less than or equal to

<= if(engineSize <= 2000)

greater than

> if(hoursWorked > 40)

greater than or equal to

>= if(age >= 18)

Foundational Java by David Parsons © 2012

Page 8: Chapter 4 Control Structures - foundjava.com

Boolean Operators

8

& AND operator (full evaluation) | OR operator (full evaluation)

Foundational Java by David Parsons © 2012

Boolean

Operator

Java

Operator

Meaning Example

AND && Return true if both

sides of the expression

are true

if(age > 4 && age < 16)

OR || Return true if at least

one side of the

expression is true

if(timeElapsed > 60 ||

stopped == true)

NOT ! Return true if the

expression is false

if(!drawingChanged)

// assumes ‘drawingChanged’

// is a boolean variable

Page 9: Chapter 4 Control Structures - foundjava.com

Exercise 4.1

• Create a class with a ‘main’ method

• In ‘main’, generate a random integer between 1 and 10 (inclusive)

• Work out of the random number is odd or even

• Using an ‘if’ statement, write an appropriate message to the console that displays both the random integer and whether it is an odd or an even number

Foundational Java by David Parsons © 2012 9

Page 10: Chapter 4 Control Structures - foundjava.com

Using Selection: the CoinExample Class

• ‘if’ statement based on using a randomly generated number to represent a coin being flipped

• The Java Math class ‘random’ operation – Returns a random double >= 0.0 and < 1.0

• Use random number in ‘if’ statement

10

double randomNumber = Math.random();

if (randomNumber < 0.5) { System.out.println("The coin shows heads"); } else { System.out.println("The coin shows tails"); }

Foundational Java by David Parsons © 2012

Page 11: Chapter 4 Control Structures - foundjava.com

Selection and Test Code

• A test compares the result you expect with the result you actually get

• Tests written in code can be run repeatedly as regression tests

11

if(dieValue >= 1 && dieValue <= 6) { System.out.println("Valid die value: " + dieValue); } else { System.out.println("Error. Expected value between 1 and 6 but was " + dieValue); }

Foundational Java by David Parsons © 2012

Page 12: Chapter 4 Control Structures - foundjava.com

‘switch’ Statement

• When multiple selections are based on a single (whole number) variable

• Switch variable and case literals must be byte, char, short or int

12

switch(variable) { case literalvalue1 : // some code here break; case literalvalue2 : // some code here break; // etc. for as many cases as need to be handled default: // default code to handle cases not already dealt with }

Foundational Java by David Parsons © 2012

Page 13: Chapter 4 Control Structures - foundjava.com

Using ‘break’ (or not)

• ‘break’ sends control to the end of the switch statement without evaluating any other cases

• Often (but not always) what you need

• Don’t use ‘break’ if you want logic shared by multiple cases

13

switch (aChar) { case ′a’ : case ′A’ : // my code here break; case ′b’ // etc…

Foundational Java by David Parsons © 2012

Page 14: Chapter 4 Control Structures - foundjava.com

Dice Man Example

• Switches on the state of a ‘die’

– No ‘default’ needed in this example

14

switch (dieValue) { case 1: System.out.println("forget the whole affair"); break; case 2: System.out.println("wait until the party on Saturday"); break; case 3: System.out.println("do what Arlene says"); break; case 4: System.out.println("have a platonic relationship"); break; case 5: System.out.println("follow your emotions"); break; case 6: System.out.println("go to Arlene’s apartment tonight"); break; }

Foundational Java by David Parsons © 2012

Page 15: Chapter 4 Control Structures - foundjava.com

‘break’ and ‘continue’

• The use of ‘break’ in a switch statement is not the only context in which this keyword can be used

– Moves execution to the end of the current block (i.e. the next closing brace)

• ‘continue’ has a similar function

– Takes control back to the beginning of the current code block rather than the end

• Useful for searching and sorting large arrays

– Act rather like structured ‘goto’ statements

15 Foundational Java by David Parsons © 2012

Page 16: Chapter 4 Control Structures - foundjava.com

Exercise 4.2 • In a ‘main’ method, generate a random integer

between 1 and 13 to represent the possible values in a suit of playing cards

• Use a ‘switch’ statement that applies cases to your random integer – If the random number is 1, print out ‘Ace’ to the console – If the random number is 11, print out ‘Jack’ to the console – If the random number is 12, print out ‘Queen’ to the

console – If the random number is 13, print out ‘King’ to the console

• The default case should simply print the random integer to the console

Foundational Java by David Parsons © 2012 16

Page 17: Chapter 4 Control Structures - foundjava.com

Ternary Operator

• Shorthand if - else statement

• If expression is true, return op1, otherwise return op2

• Used when intent is to focus on returned result, rather than a branch in program flow

17

String result = x % 2 == 0 ? "even" : "odd";

expression ? op1 : op2

Foundational Java by David Parsons © 2012

Page 18: Chapter 4 Control Structures - foundjava.com

Iteration • Iteration can be achieved in three slightly different

ways: – ‘while’ loops – ‘do...while’ loops – ‘for’ loops

• In each case, there will be a condition that allows the loop to terminate

• Which one to use depends on a number of factors and we often find that more than one will meet our requirements – We have to be aware of their differences in order to use

them correctly

18 Foundational Java by David Parsons © 2012

Page 19: Chapter 4 Control Structures - foundjava.com

‘while’ and ‘do…while’

• These loops continue while the condition is true

– ‘while’ tests a precondition (zero or more iterations)

– ‘do…while’ tests a post condition (one or more iterations)

19

do { // statements } while(condition); Note the semicolon!

while(condition)

{

// statements

}

Foundational Java by David Parsons © 2012

Page 20: Chapter 4 Control Structures - foundjava.com

‘do…while’ example

• This ‘do…while’ loop simulates the throwing of a die until it shows a six

20

int dieValue = 0; // loop until throwing the Die gets a six do { // generate a random number in the range 0.0 to 1.0 double randomNumber = Math.random(); // to get a number in the range 1 to 6, we need to multiply the // random number by 6 and add 1 randomNumber *= 6; randomNumber++; // to convert this value into an integer we cast it dieValue = (int)randomNumber; System.out.println("You have thrown a " + dieValue); } while (dieValue != 6);

Foundational Java by David Parsons © 2012

Page 21: Chapter 4 Control Structures - foundjava.com

‘for’ Loops

• Statement has three sections

– initialise - executed once before loop begins

– condition - executed before each loop

• If true then loop body executes

– update - executed at the end of each loop

21

for(initialisation; 'while' condition; action) { // some code here }

Foundational Java by David Parsons © 2012

Page 22: Chapter 4 Control Structures - foundjava.com

Initialisation and Update

• Any or all of the three sections can be left empty

– This is an endless loop

• Only use a ‘for’ loop when you need initialisation and update actions

– Otherwise code is more complex that it needs to be

– e.g. endless ‘while’ loop is simpler

22

for(;;)

{...

while(true) {…

Foundational Java by David Parsons © 2012

Page 23: Chapter 4 Control Structures - foundjava.com

Iteration with a ‘for’ Loop

• This example uses a ‘for’ loop to display the printable ASCII characters of the Unicode table

23

// the 'for' loop counts from 33 to 126, the range of the printable ASCII characters for (int i = 33; i < 127; i++) { // convert the integer to a 'char' using a cast char character = (char)i; // display the ASCII number along with its character then add a tab System.out.print(i + ": " + character + '\t'); // if there are 9 characters on a row, add a line feed if ((i - 32) % 9 == 0) { System.out.println('\n'); } }

Foundational Java by David Parsons © 2012

Page 24: Chapter 4 Control Structures - foundjava.com

‘for’ loops and arrays

• for loops are frequently used to loop through arrays – Use the array’s length field to control the loop

– Note the use of two arrays – one of ints and the other of Strings

24

String[] monthNames = {"January","February","March","April","May","June","July","August", "September","October","November","December"}; int[] monthlyRainfall = {74,81,86,93,100,116,126,111,93,80,84,91}; System.out.println("Average monthly rainfall"); for(int i = 0; i < monthlyRainfall.length; i++) { System.out.println(monthNames[i] + ": " + monthlyRainfall[i] + "mm."); }

Foundational Java by David Parsons © 2012

Page 25: Chapter 4 Control Structures - foundjava.com

Iterating through the array passed to ‘main’

• The parameter we always use with ‘main’ is an array of Strings, which may or may not be empty

• The size of this array depends entirely on how many Strings are passed to it at run time

25

public static void main(String[] args) { for (int i = 0; i < args.length; i++) { System.out.println(args[i]); } }

Foundational Java by David Parsons © 2012

Page 26: Chapter 4 Control Structures - foundjava.com

Passing Strings to ‘main’

• From the command line…

• In Eclipse…

– ‘Run’ -> ‘Run Configuration…’

26

java com.introjava.chapter4.MainArrayLoopExample hello I am some strings

Foundational Java by David Parsons © 2012

Page 27: Chapter 4 Control Structures - foundjava.com

Multiple Initialisations and Actions

• The initialisation and action sections of the ‘for’ statement can contain lists of values, separated by commas

27

public class MultiValueForLoopExample { public static void main(String[] args) { for (int letterCount = 1, upperCount = 65, lowerCount = 97; letterCount <= 26; letterCount++, upperCount++, lowerCount++) { System.out.println("Lower case: " + (char)lowerCount + " Upper case: " + (char)upperCount); } } }

Foundational Java by David Parsons © 2012

Page 28: Chapter 4 Control Structures - foundjava.com

Exercise 4.3

• Create a new class with a ‘main’ method. In ‘main’, take the following steps – Create and initialise an array containing the integers 1,

2, 3, 4, 5, 6, 7, 8, 9 and 10

– Use a ‘for’ loop to print out the contents of the array

– Add a ‘while’ loop that prints out the contents of the array in reverse order

– Add a ‘do..while’ loop that iterates forward through the array. Inside the loop, add an ‘if’ statement so that only even numbered values from the array are printed

28 Foundational Java by David Parsons © 2012

Page 29: Chapter 4 Control Structures - foundjava.com

Summary

• Control structures for selection and iteration • Selection syntax

– ‘if’ and ‘switch’ statements

• Relational and Boolean operators • Different kinds of loop

– ‘while’, ‘do…while’, ‘for’

• Iterating through arrays • Math class for random number generation • Passing an array of Strings to the main method of

a class at run time

Foundational Java by David Parsons © 2012 29