30/04/20151 4.3 Selection Nested If structures & Complex Multiple Conditions.

32
21/03/22 21/03/22 1 4.3 Selection 4.3 Selection Nested If structures Nested If structures & & Complex Multiple Complex Multiple Conditions Conditions

Transcript of 30/04/20151 4.3 Selection Nested If structures & Complex Multiple Conditions.

18/04/2318/04/23 11

4.3 Selection4.3 Selection

Nested If structuresNested If structures

&&

Complex Multiple ConditionsComplex Multiple Conditions

22

Learning ObjectivesLearning Objectives

State what is needed for each State what is needed for each IfIf statement statement in in Nested If StructuresNested If Structures..

State which has precedence: State which has precedence: AndAnd / / Or Or Boolean statements Boolean statements and note that this and note that this can cause problems in complex multiple can cause problems in complex multiple conditions.conditions.

33

Nested If StructuresNested If Structures

An alternative to using multiple And An alternative to using multiple And conditions.conditions.

44

Multiple Multiple And And Boolean StatementBoolean Statement

So instead of using a multiple So instead of using a multiple AndAnd condition like:condition like:

55

MultipleMultiple And And Boolean StatementBoolean Statement

Dim Age As IntegerDim Age As IntegerDim Gender As StringDim Gender As StringAge = txtAge.TextAge = txtAge.TextGender = txtGender.TextGender = txtGender.TextIf (Age >= 18) And (Gender = “F”) Then If (Age >= 18) And (Gender = “F”) Then ‘ Female ‘ Female ‘ 18 and over?‘ 18 and over? MsgBox (“Allow into nightclub.”)MsgBox (“Allow into nightclub.”)

Else Else ‘ Everybody else‘ Everybody else MsgBox (“Do not allow into nightclub.”)MsgBox (“Do not allow into nightclub.”)

End IfEnd If

66

Nested Nested IfIf Structure Structure

We could use:We could use:

77

Nested Nested IfIf Structure StructureDim Age As IntegerDim Age As Integer

Dim Gender As StringDim Gender As String

Age = txtAge.TextAge = txtAge.Text

Gender = txtGender.TextGender = txtGender.Text

If Age >= 18 Then If Age >= 18 Then ‘Aged 18 or over?‘Aged 18 or over? If Gender = “F” Then If Gender = “F” Then ‘and female?‘and female?

lblMessage.Text = “Allow into nightclub.”lblMessage.Text = “Allow into nightclub.” Else Else ‘All other people.‘All other people.

lblMessage.Text = “Do not allow into nightclub!”lblMessage.Text = “Do not allow into nightclub!” End IfEnd If

End IfEnd If

11 22

88

Nested Nested IfIf Structures Structures

We can also replace We can also replace ElseIfElseIf structures with structures with nested nested IfIf structures. structures.

99

ElseIfElseIf structures structures

So instead of:So instead of:

1010

ElseIfElseIf structures structures

Dim Mark As IntegerDim Mark As IntegerMark = InputBox(“Enter an exam mark from 0 to Mark = InputBox(“Enter an exam mark from 0 to 100.”)100.”)If Mark >=60 Then If Mark >=60 Then ‘Mark 60 or more?‘Mark 60 or more? MsgBox (“Merit”)MsgBox (“Merit”)

ElseIf Mark >= 40 Then ElseIf Mark >= 40 Then ‘Mark 40 - 59?‘Mark 40 - 59? MsgBox (“Pass”)MsgBox (“Pass”)

Else Else ‘Mark under 40.‘Mark under 40. MsgBox (“A mark of “ & Mark & “ is a fail.”)MsgBox (“A mark of “ & Mark & “ is a fail.”)

End IfEnd If

1111

Nested Nested IfIf Structures Structures

We can use:We can use:

1212

Nested Nested IfIf Structures Structures

If Mark >=60 Then If Mark >=60 Then ‘Mark 60 or more?‘Mark 60 or more? MsgBox (“Merit”)MsgBox (“Merit”)

ElseElse If Mark >= 40 Then If Mark >= 40 Then ‘Mark 40 - 59?‘Mark 40 - 59?

MsgBox (“Pass”)MsgBox (“Pass”) Else Else ‘Mark under 40.‘Mark under 40.

MsgBox (“A mark of “ & Mark & “ is a fail.”)MsgBox (“A mark of “ & Mark & “ is a fail.”) End IfEnd If

End IfEnd If

11 22

1313

Nested Nested IfIf Structures Structures

Note:Note: If you use nested If you use nested IfIf structures you need to structures you need to

remember to use an remember to use an EndEnd IfIf statement for statement for each each IfIf statement. statement.

1414

Program 4.3 Rent a propertyProgram 4.3 Rent a property

Specification:Specification: Illustrate complex multiple conditions:Illustrate complex multiple conditions:

More specifically to illustrate the order of More specifically to illustrate the order of precedence of the precedence of the AndAnd & & OrOr logical operators. logical operators.

A customer wants to rent a holiday property A customer wants to rent a holiday property which has 4 or more bedrooms, and it must which has 4 or more bedrooms, and it must be a cottage or a detached house.be a cottage or a detached house.

1515

Program 4.3 Rent a propertyProgram 4.3 Rent a property

Create a new project named ‘Create a new project named ‘Rent a Rent a propertyproperty’.’.

Change the form’s Change the form’s TextText property to ‘ property to ‘Rent Rent a propertya property’.’.

1616

The FormThe Form

Two labels. Two labels.

Two list boxes.Two list boxes.

One button.One button.

Set their text / item Set their text / item properties as properties as shown on the form shown on the form opposite.opposite.

1717

Program 4.3 Rent a propertyProgram 4.3 Rent a property

Name the list boxes Name the list boxes lstTypeslstTypes and and lstBedroomslstBedrooms as appropriate. as appropriate.

Name the button Name the button butRentbutRent..

1818

Program 4.3 Rent a propertyProgram 4.3 Rent a property

butRent code:butRent code: If (lstTypeIf (lstTypess.Text = "Cottage") Or .Text = "Cottage") Or

(lstType(lstTypess.Text = "Detached") And .Text = "Detached") And ((lstlstBedroomsBedrooms.Text.Text > >== 4) Then 4) Then

MsgBox("Rent it!")MsgBox("Rent it!") ElseElse

MsgBox("Don’t rent it!")MsgBox("Don’t rent it!") End IfEnd If

1919

Program 4.3 Rent a propertyProgram 4.3 Rent a property

Run the program and test all possibilities.Run the program and test all possibilities.

You should find a problem! What is it?You should find a problem! What is it?

2020

Program 4.3 Rent a propertyProgram 4.3 Rent a property

You should have found that if it is a You should have found that if it is a cottage and the number of bedrooms is cottage and the number of bedrooms is lower than 4 the program still says ‘lower than 4 the program still says ‘Rent Rent it!it!’.’.

2121

Program 4.3 Rent a propertyProgram 4.3 Rent a property

This is because This is because AndAnd is done before is done before OrOr..

So the program interprets the code like this:So the program interprets the code like this: (lstType(lstTypess.Text = "Cottage").Text = "Cottage") OrOr (lstType(lstTypess.Text = "Detached") .Text = "Detached") AndAnd ( (lstlstBedroomsBedrooms.Text.Text > >== 4) 4)

So if it is Detached then this works as both the type and So if it is Detached then this works as both the type and the number of bedrooms has to be true but if it is a the number of bedrooms has to be true but if it is a cottage then the type cottage then the type oror the number of bedrooms is the number of bedrooms is required to be true; so it doesn’t work.required to be true; so it doesn’t work.

2222

Program 4.3 Rent a propertyProgram 4.3 Rent a property

Replace the Rent button’s template code Replace the Rent button’s template code with:with: If (lstTypeIf (lstTypess.Text = "Cottage") And (.Text = "Cottage") And (lstlstBedroomsBedrooms.Text.Text

>>== 4) 4) Or (lstTypeOr (lstTypess.Text = "Detached") And .Text = "Detached") And ((lstlstBedroomsBedrooms.Text.Text > >== 4) Then 4) Then

MsgBox("Rent it!")MsgBox("Rent it!") ElseElse

MsgBox("Don’t rent it!")MsgBox("Don’t rent it!") End IfEnd If

2323

Program 4.3 Rent a propertyProgram 4.3 Rent a property

Run the program and test all possibilities.Run the program and test all possibilities.

It should work perfectly now.It should work perfectly now.

2424

Extension “Work Hours” Program 1Extension “Work Hours” Program 1

For each employee the hours worked module collects For each employee the hours worked module collects data for five days. data for five days. If the user leaves a day empty give a message box If the user leaves a day empty give a message box asking the user to enter a 0.asking the user to enter a 0.

Use one If with either Use one If with either AndAnd / / OrOr – you will need to think/find out – you will need to think/find out which is suitable.which is suitable.

Each person can work up to 9 hours a day for up to 5 Each person can work up to 9 hours a day for up to 5 days a week. days a week.

Use one If with either Use one If with either AndAnd / / OrOr – you will need to think/find out – you will need to think/find out which is suitable.which is suitable.

No-one may work more than 40 hours.No-one may work more than 40 hours.If all the above requirements are met then the hours are If all the above requirements are met then the hours are added up and displayed.added up and displayed.

I suggest 5 text boxes (one for each day), a button and a label to I suggest 5 text boxes (one for each day), a button and a label to display the Total Number of Hours worked.display the Total Number of Hours worked.

252518/04/2318/04/23

ConcatenationConcatenation

contents of the contents of the NameName variable variable contents of the contents of the AgeAge variable variable

Note the spaces needed to create a readable message.Note the spaces needed to create a readable message.

Join variables and strings together using Join variables and strings together using the the && operator. operator. e.g. Putting a variable in a message:e.g. Putting a variable in a message:

MsgBox (Name MsgBox (Name && “, you are “ “, you are “ && Age Age && “ years “ years old.”)old.”)

Will show:Will show:

…… …… , you are … years old., you are … years old.

2626

Extension “Vehicle Type” Program 2Extension “Vehicle Type” Program 2

Vehicle Type:Vehicle Type:

EnterEnter

See the next slide for more details.See the next slide for more details.

2727

Extension “Vehicle Type” Program 2Extension “Vehicle Type” Program 2

Write a program to allow only car, motorbike and Write a program to allow only car, motorbike and lorry as valid vehicle types.lorry as valid vehicle types.

Note that you must declare a variable to store the vehicle type so Note that you must declare a variable to store the vehicle type so this will be the “first” time you will need to declare a variable as this will be the “first” time you will need to declare a variable as “String” as it will not be a number.“String” as it will not be a number.

Invalid vehicle types should produce the error message: Invalid vehicle types should produce the error message: ““InvalidInvalid”.”.

Use one If with either Use one If with either AndAnd / / OrOr – you will need to think/find out – you will need to think/find out which is suitable.which is suitable.

Valid vehicle types should produce a message:Valid vehicle types should produce a message: …….... is validis valid

Does the program also accept Car, Does the program also accept Car, Motorbike and Lorry?Motorbike and Lorry?

Find out but do not attempt to change this.Find out but do not attempt to change this.

Please explain what happens and why in Please explain what happens and why in your comments.your comments.

vehicle typevehicle type

Hint: Use Hint: Use concatenation – see previous slides. – see previous slides.

2828

Extension Program “Password Attempts” 3Extension Program “Password Attempts” 3

Password:Password:

EnterEnter

See the next slide for more details.See the next slide for more details.

EnterEnterEnterEnter

Password:Password:

EnterEnter

See the next slide for more details.See the next slide for more details.

Password:Password:

2929

Extension Program “Password Attempts” 3Extension Program “Password Attempts” 3

You choose the password but it must be You choose the password but it must be a combination of letters and numbers.a combination of letters and numbers.

Write a program that will check an entered Write a program that will check an entered password.password. First test if the password the user has entered is First test if the password the user has entered is

correct.correct.If PasswordEntered = “…….”If PasswordEntered = “…….”

If the password is correct then display a suitable message e.g. If the password is correct then display a suitable message e.g. ““Password CorrectPassword Correct!”.!”.

If the password is incorrect then increment the number of If the password is incorrect then increment the number of attempts by one.attempts by one.

Hint: Do you need a global variable?Hint: Do you need a global variable?

If Attempt = 1, output “If Attempt = 1, output “First try is wrong. Please try First try is wrong. Please try again.again.””

On the second try output “On the second try output “Password still wrong. One Password still wrong. One more chance.more chance.””

On the third try output “On the third try output “No valid password entered.No valid password entered.””

3030

Extension “Winner or Winners” Extension “Winner or Winners” Program 4Program 4

Write a program to accept three marks for three Write a program to accept three marks for three candidates candidates Candidate ACandidate A, , Candidate BCandidate B and and Candidate CCandidate C..The program should display the winner The program should display the winner (highest mark).(highest mark).

Extension:Extension:Adapt the program to deal correctly with three or two of the Adapt the program to deal correctly with three or two of the candidates receiving equal marks.candidates receiving equal marks.

Hints:Hints: 1.1. Test for clear winners first, then for three winners and then for two Test for clear winners first, then for three winners and then for two

winners.winners.2.2. Either use:Either use:

A series of A series of ElseIfElseIf statements. statements.

OrOr Separate If statements with Separate If statements with Exit SubExit Sub after each winner is declared after each winner is declared

So as to help make other IF’s less complicated or run the chance So as to help make other IF’s less complicated or run the chance of a correct winner being replaced by incorrect winners later on in of a correct winner being replaced by incorrect winners later on in the program.the program.

3131

Extension “Mouse Clicks” Program 5Extension “Mouse Clicks” Program 5

Extend the “Global Variables/Mouse Clicks” program:Extend the “Global Variables/Mouse Clicks” program: 3.2 Working with Data

Rename the original button as “Button A” and add two similar Rename the original button as “Button A” and add two similar buttons “Button B” and “Button C”.buttons “Button B” and “Button C”.The program should record how many times each button is The program should record how many times each button is clicked but should no longer display these numbers on the clicked but should no longer display these numbers on the screen as they are clicked. screen as they are clicked. Instead, add an extra “Winner” Instead, add an extra “Winner” buttonbutton which, when clicked, displays, the which, when clicked, displays, the name of the button name of the button which was clicked the most times which was clicked the most times (i.e. the “Winner”).(i.e. the “Winner”).

Also either:Also either: Add a “Reset” button.Add a “Reset” button.OrOr Declare the “The winner/s was/were” and then reset automatically.Declare the “The winner/s was/were” and then reset automatically. Do not use “Application.Reset” as exams will not allow you to use this Do not use “Application.Reset” as exams will not allow you to use this

“simplistic” way. “simplistic” way. Please use the more “manual complex” way.Please use the more “manual complex” way.

3232

PlenaryPlenary

What is needed for each What is needed for each IfIf statement in statement in Nested If StructuresNested If Structures?? End IfEnd If

Which has precedence: Which has precedence: AndAnd / / OrOr?? AndAnd