NESTING CONDITIONAL LOGIC


Sometimes the logic that you are developing may be too complicated to be represented using the different variations of the IfThen statements. However, you can greatly extend the power of the IfThen statements by nesting them within one another. This enables you to develop logic that tests for one condition and then further tests other conditions based on the result of the previous test.

image from book
DEFINITION

Nesting is the process of embedding one statement within another statement of the same type, such as when you embed IfThen statements in order to develop more complicated conditional logic.

image from book

You've already seen examples of nested If statements in previous chapter game projects. For example, the following code comes from the btnDone_C1ick event belonging to the Speed Typing game that you worked on in Chapter 3.

 If intwrong = 3 Then 'If intWrong equals three the player has struck out      'Time to determine the player's typing skill level      If intCount < 2 Then  'Set rank when less than 2 tests were passed           MessageBox.Show("Game over. Your typing skill level " _                & "is: Beginner. Please play again!")           intCount = 0           intWrong = 0           Return 'Exit procedure immediately      End If      If intCount < 4 Then 'Set rank when less than 4 tests, were passed           MessageBox.Show("Game over. Your typing skill level " _                 & "is: Intermediate. Please play again!")           intCount = 0           intWrong = 0           Return  'Exit procedure immediately      End If      If intCount < 5 Then 'Set rank when less than 5 tests were passed           MessageBox.Show("Game over. Your typing skill level " _                & "is: Advanced. Please play again!")           intCount = 0           intwrong = 0           Return  'Exit procedure immediately      End If End If 

In the Speed typing game, the game is set up to end if the player gets three strikes. The number of strikes made by the player is stored in the intWrong variable. The game also tracks the number of typing tests passed by the player by incrementing the value assigned to the intCounter variable.

In this example, the value of intWrong is first evaluated to see if it is equal to 3. If it is, then a series of three embedded IfThen statements are executed, each of which further refines the analysis by checking the value assigned to the intCount variable.

Trap 

You can embed as many IfThen statements as you want within one another. However, the deeper you go, the more difficult your program code will be to PP read and maintain.




Microsoft Visual Basic 2005 Express Edition Programming for the Absolute Beginner
Microsoft Visual Basic 2005 Express Edition Programming for the Absolute Beginner
ISBN: 1592008143
EAN: 2147483647
Year: 2006
Pages: 126

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net