36
1 Week 4 Selection (if..then..else), and Compound Conditions.

1 Week 4 Selection (if..then..else), and Compound Conditions

Embed Size (px)

Citation preview

1

Week 4

Selection (if..then..else),

and

Compound Conditions.

Extra support for java• There will be a drop in session in MI206/207 for

anyone who needs extra help with java at 3pm on Mondays.

• All you need to do is go along at 3, and there will be staff who will be able to work with you 1:1 to help with anything you are struggling with.

• If you are having any problems with java please do attend these extra sessions

CP1105 - Lecture 3 2

3

Last week on 4CS001

4

Boolean variables are either true or false

boolean isEnrolled = false;

boolean hasPassed = grade > 40;

Operator Meaning == equal!= not equal< less than

<= less than or equal> greater than

>= greater than or equal

Relational operators

Note the difference between assignment and equality

Boolean Variables and Expressions

Boolean variables can also store the result of relational expressions

5

char Data Type• A variable of type char can store one character.

char oneCharacter = 'w';

System.out.println(oneCharacter);

w

data type

variablename character

literal

character literals are enclosed in single quotes

6

String word1 = "Java";

String word2 = "Java";

System.out.println("same=" + word1.equals(word2));

equals returns a boolean value true if both strings contain the same sequence of characters false if the character sequence is different.

equalsIgnoreCase can be especially useful

In this example same = true

String Equality

7

String Methods• int length()

– Returns the number of characters in the String– will include the space character if there are any

• int indexOf(char)– Returns the index of the first occurrence of the char

• int lastIndexOf(char)– Returns the index of the last occurrence of the char

• String replaceAll(String old, String new)• String toUpperCase()• String toLowerCase()

8

• boolean startsWith(String)– returns true is the string starts with the string in the

parameter

• boolean endsWith(String)– returns true is the string ends with the string in the

parameter• char charAt(int index)

– Returns the character at specified index.• String substring(int beginIndex)

– Returns the characters of the string following index• String substring(int beginIndex, int endIndex)

– Returns the characters between (but not including) both the indices

String Methods

9

• There are 3 fundamental concepts of Structured Programming:

• Sequence– One (instruction) statement follows another and the

program executes them in sequence.• Selection

– The next statement to be executed depends on the value of an expression.

• Iteration– A section of the program may be repeated multiple

times.• Any program can be constructed with these.• Other concepts exist but are not essential

– e.g. Iteration can be replaced with recursion

Programming Building Blocks

• An activity diagram consists of activities (enclosed in rounded rectangles).

• Arrows show the sequence in which activities are followed (the control flow).

• Diamonds indicate branches to alternative actions (decision points).

• Selection guards (expressions between square brackets) determine the control flow.

• A filled circle and a bulls eye mark the start and end respectively.

[boolean expression]

Activity Diagrams

Jeliot

11

12

Homework for last week was• Read chapter 5 of Currie• Read the supporting notes on Wolf for Week 3• Attempt the new Jafa exercises• Run Jeliot• Finish the workshop for week 3• Do the Quiz for Week 3 and put your answers onto the Wolf

Programming forum• We assume that you have done these tasks.• If you do not keep up-to-date you will find the module tasks

more and more difficult to understand.• If you need help with any workshop exercises outside the

normal class time come along to the surgery classes.

13

Lecture 4

Compound conditions

14

Assessment (recap)• Portfolio

– 1. An online test in teaching week 7– 30 questions

20 marks about dry running some code 10 marks for debugging questions and code snippets

– 2. time constrained programming exercises in Assessment week after Christmas

• You must make a reasonably good attempt at each of the two parts of the portfolio to pass the module

• If you fail you will have an opportunity to resit next year but your grade will be capped to a bare pass.

Lecture Objectives• To re-iterate the concepts of:-

– Compound conditions– Problem solving

• The outcome of the lecture will be:– To be able to use compound conditions in algorithm design– To be able to code nested if…then…else statements in Java

if – else (recap)

• The instructions in the ThenClause are executed if the Boolean expression evaluates to true.

• The instructions in the ElseClause are executed if the Boolean expression evaluates to false.

( ThenClauseBooleanExpif )

ElseClauseelse

Compound conditions• Last week we considered an example where a student

must achieve at least 40% to pass a test.– If the result is 40% or more then the test has been passed,

otherwise the test is failed.– Algorithm for this is

1 Get the mark

2 IF the mark is greater than or equal to 40

THEN the test is passed

ELSE the test is failed

• Consider, instead of telling students that they have passed or failed, the system tells them what grade they achieved.

1

2

3

4

5

6

7

8

9

10

11

if(marks >= 70)

grade = "A";

if(marks >= 60 && marks < 70)

grade = "B";

if(marks >= 50 && marks < 60)

grade = "C";

if(marks >= 40 && marks < 50)

grade = "D";

if(marks <40)

grade = "Fail";

}

If a student is awarded an ‘A’, tests are still made to see if they should be awarded the other grades.

if – then

Dry run for this

1 int marks = 50

2 if(marks >= 70)

3 grade = "A";

4 if(marks >= 60 && marks < 70)

5 grade = "B";

6 if(marks >= 50 && marks < 60)

7 grade = "C";

8 if(marks >= 40 && marks < 50)

9 grade = "D";

10 if(marks <40)

11 grade = "Fail";

CP1105 - Lecture 3 19

L marks marks>=70

Marks>=60&&<70

Marks>=50&&<60

Marks>=40&&<50

Marks < 40

grade

1 50

2 F

4 F

6 T

7 C

8 F

10 F

Nested if ..then.. else.. statements• The statements belonging to each branch of the then or the

else can themselves be further if.. then..else ..statements• The Algorithm could then be:-

IF mark is greater than or equal to 70 THEN “A”

ELSE IF mark is greater than or equal to 60 THEN “B”

ELSE IF mark is greater then or equal to 50 THEN “C”

ELSE IF mark is greater than or equal to 40 THEN “D”

ELSE IF mark is greater then or equal to 35 THEN “E”

ELSE “F”

• By convention to make it clearer how the IF, THEN, ELSE pair up we INDENT each successive IF to show the STRUCTURE of the algorithm.

If the result is an ‘A’ no more conditions are checked.

Indented Mark Grading AlgorithmIF mark is greater than or equal to 70

THEN “A”ELSE

IF mark is greater than or equal to 60 THEN “B”

ELSE IF mark is greater then or equal to 50 THEN “C”

ELSE IF mark is greater than or equal to 40 THEN “D” ELSE IF mark is greater then or equal to 35 THEN “E” ELSE “F”

• Exercise – What would the algorithm look like as an Activity Diagram?

Activity Diagram

22

[mark >= 70]

Input mark

[mark >= 60]

Output “A”

Output “B”

[mark >= 50]

Output “C”

Mark Grading Java Code• The above algorithm expressed as java code could be

if (mark >= 70)grade = “A”;

else if (mark >= 60) grade = “B”; else if(mark >= 50)

grade = “C”;else if (mark >= 40)

grade = “D”;else if(mark >= 35)

grade = “E”;else grade = “F”;

• The layout of the code is important

1. int mark = 72;2. if (mark >= 70)3. grade = “A”;4. else if (mark >= 60)5. grade = “B”;6. else if(mark >= 50)7. grade = “C”;8. else if (mark >= 40)9. grade = “D”;10. else if(mark >= 35)11. grade = “E”;12. else grade = “F”;13. System.out.print(grade)

Dry Run on above Code – assume mark is 72

Line No

Mark Mark>=70

Mark>=60 Mark>=50

Mark>=40

Mark>=35

Grade Output

1 72

2 T ? ? ? ?

3 A

13 A

Original Algorithm as Activity Diagram

[mark >= 40]

Input mark

[mark < 40]

Output “Passed” Output “failed”

mark<40?

Consider a module grading system where the student must pass both a test and a piece of coursework. If the test result is less than 40, or the coursework result is less than 40, then the student fails the module.

[passed both test and exam]

Output “Failed”Output “Passed”

Compound Conditions

[failed either the test or the coursework]

Input test marks and coursework marks

if(testMark >= 40 && cWorkMark >= 40)

JOptionPane.showMessage("You have Passed");

else

JOptionPane.showMessage("You have Failed");

Equivalence of Boolean expressions

• We can find out whether the test has been passed in two slightly different ways:– testMark >= 40 is the same as !(testMark < 40)

– Which reads as “testMark greater than or equal to 40” is the same as “not testMark less than 40”

28

LogicThe Boolean expression should be made as clear and readable as possible, but they can be combined using the following operators: ! (not) && (and) || (or)Which may be complicated.

“If (Age is less than 60 and Queue is not full or Bribe is greater than 2000) then (carry out instructions)”

This condition is ambiguous. - e.g. does “and” take precedence over “or”?

- we need rules to govern our logic similar to BODMAS.

Therefore we have the rule that “and” does take precedence over “or”.

29

Boolean ExpressionsConsider “Age > 18 && Age < 65”If we want to negate this (state the opposite)

WRONG WAY: “Age is NOT greater than 18 AND Age is NOT less than 65”

- think about it - this would be true for nobody (you can’t be <18 years old and > 65 years old at the same

time)

RIGHT WAY: “Age is NOT greater than 18 OR Age is NOT less than 65”

1 int testMark = 39;

2 int cWorkMark = 41;

3 if(testMark >= 40 && cWorkMark >= 40)

4 JOptionPane.showMessage("You have Passed");

5 else

6 JOptionPane.showMessage("You have Failed");

Dry Run on Pass Fail Code

Line No testMark cWorkMark testMark>=40 cWorkMark>=40 testMark>=40 && cWorkMark>=40

Output

1 int testMark = 39;

2 int cWorkMark = 41;

3 if(testMark >= 40 && cWorkMark >= 40)

4 JOptionPane.showMessage("You have Passed");

5 else

6 JOptionPane.showMessage("You have Failed");

Dry Run on Pass Fail Program

Line No testMark cWorkMark testMark>=40 cWorkMark>=40 testMark>=40 && cWorkMark>=40

Output

1 39

2 41

3 FALSE TRUE FALSE

6 “You have Failed”

Starting from scratch – solving a problem

Take this problem from your workbook:

You are asked to create a program which will check to see if someone is eligible to go on an 18-30 holiday.

You need to find out their age first of all, and then you need to test to see if they are between 18 – 30. If they are, they are eligible, otherwise they are not.

So, firstly draw an activity diagram (see next slide):

CP1105 - Lecture 3 32

[age<18 || age>30]

Output “You are eligible”Output “You are not eligible”

Holidays

[NOT age<18 || age>30]

Get age

So, what do you need as variables• You need to use JOptionPane so the user can input their age, and you need

an integer so that you can use ‘parseInt’ to store that age as an integer.import javax.swing.JOptionPane;

public class Holidays1 {

public static void main(String[] args) {

String ageText = JOptionPane.showInputDialog(null, "Please enter your age:");

int age = Integer.parseInt(ageText);

• Then you need to test the age to see if the applicant is eligible:if(age<18 || age>30) {

System.out.println("You are not eligible for the holiday");

} else {

System.out.println("You are eligible for the holiday");

}

}

}

CP1105 - Lecture 3 34

Reminder Extra support for java• There will be a drop in session in MI206/207 for

anyone who needs extra help with java at 3pm on Mondays.

• If you are having any problems with java please do attend these extra sessions

CP1105 - Lecture 3 35

Workshop Exercises

1. You should be working on Week 4 workshop this week

36