Branching with the If . . . Then . . . Else Decision Statement - 06
- Posted: Nov 21, 2011 at 9:25 AM
- 30,632 Views
- 23 Comments
Loading User Information from Channel 9
Something went wrong getting user information from Channel 9
Loading User Information from MSDN
Something went wrong getting user information from MSDN
Loading Visual Studio Achievements
Something went wrong getting the Visual Studio Achievements
Right click “Save as…”
Branching allows us to add logic to our applications. In this lesson you're introduced to the If Decision statement (in its various forms) as well as the IIf conditional function. We also discuss how to refactor our code to make it more compact and less likely to produce errors by eliminating duplicate code.
Already have a Channel 9 account? Please sign in
Follow the Discussion
Oops, something didn't work.
What does this mean?
Following an item on Channel 9 allows you to watch for new content and comments that you are interested in. You need to be signed in to Channel 9 to use this feature.What does this mean?
Following an item on Channel 9 allows you to watch for new content and comments that you are interested in and view them all on your notifications page.sign up for email notifications?
Very cool love the example in the end. Never knew about the {0} and the iif, really cool!
Can I use if, else, in Access? If so how?
@Algorithum: Cool!
@Joe: Sorry, I am NOT an Access or vbScript guy so I'll have to rely on someone else to answer definitively. (I'm betting you can, though.)
I would like to use a goto statement with if else then statement here to create some loops.
Could we build loops using only if else then statements?
This lesson is very informative. Loved it! Thanks.
Hi Bob. When try to add a word inside of a sentence, it deletes the letter in front of it. How do i fix this?
@halitates: I suppose, but I would encourage you to use for ... next, while, do .. while, etc. The use of "goto" has become a "religious battle" with some claiming it indicates bad code and others claiming it's just fine. I generally stay away from it ... the statements I demonstrate are generally considered to be "safe".
@Austin Enos: Wild. Could you post your code? I promise to take a look at it and help you figure it out.
@bobTabor Thanks for such nice & informative video .... this video will helpful for the beginners....
please Add some Extra videos with other useful Commands and Examples...
at last ... Please Add Videos on the Development of "Windows notification area" Thanks
@Jag mohan: Thanks for the nice note! The best place to make these requests (and convey your compliments)? That little Feedback icon in the footer of this site. Microsoft reads those more closely and they will contact me (or someone more qualified) to build out that content you're looking for. They DO listen, in my experience. Best wishes!
Thank you BOB for those videos .
Even I really got very sad because you did not respond me to all my letter on learnvisualstio.net
I still love you , and I appreciate the way you make lessons easy to understand for somebody who even knows nothing about alogarythim or whatever more.
And for sure this is my case .
@Mbonga: Hi and sorry you didn't get a reply ... I have someone filtering messages because I get quite a few and I have to find some time to actually do work.
Please write me directly ... bob at learn visual studio dot net and I'll try to help if I can. Best wishes!
When I try to follow the example, I get an error message that says: Console.WriteLine is a value and therefore cannot be the target of the assignment.
When I try to follow the elseif example, the console.write doesn't write with 1, 2, or 3. It does write with the last choice.
When I try to follow the elseif example, the console.write doesn't write with 1, 2, or 3. It does write with the last choice.
@Ginny: Hi Ginny, I'm betting that you have a really small error in your code. You can post it directly in here and I can help you find the problem, OR you could simply look very very closely at your syntax. It's possible you're missing a single character ... it has to be EXACT.
Don't worry, you get better at it with practice. Feel free to post your exact code right here and I'll help if I can.
opening thread
Hi!
Great work on these vids Bob. Clear and concise and newbie friendly.
Ok. I have watched a few vids and I am just playing around with a few things but there is something I would like explained please.. Here is an example that I hope will help to understand my question...
**edit** sorry, after posting and reading I noticed that my code didn't paste in quite right with some lines being broken up into multiple lines, its obvious where this has happened so I doubt it will cause any misunderstanding. Just thought I would clarify incase you thought it was the way I actually typed it into the IDE... Anyways-----
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Console.WriteLine("Please enter your name.")
Dim userName As String = Console.Readline
Console.WriteLine("Ok then " & userName & ". You stand in a room with three doors. One
red, one blue and one green." & vbCrLf & " <enter to continue> ")
Console.ReadLine()
Console.WriteLine("It's a simple choice " & userName & ", pick a colour." & vbCrLf & "<red>"
& vbCrLf & "<blue>" & vbCrLf & "<green>")
Dim doorChoice As String = Console.Readline()
Dim doorChoiceMessage = ""
If doorChoice = "red" Then
doorChoiceMessage = "You open the red door and are instantly engulfed in flames. Death!"
ElseIf doorChoice = "blue" Then
doorChoiceMessage = "You open the blue door and are pounded by a tidal wave, drowning
you. Death!"
ElseIf doorChoice = "green" Then
doorChoiceMessage = "You open the green door and step inside. A lush garden bustling
with life takes you quite by suprise."
Else doorChoiceMessage = "You couldn't make a decision. You feel your lungs start to burn as
the room fills with a noxious gas. You slowly drift away into........ Death!"
End If
Console.WriteLine(doorChoiceMessage)
Console.ReadLine()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Now, my problem is that I don't know how to move the code along after the correct choice is made (ie: green) If I simply place another WriteLine at the bottom it will proceed to that BUT it will also go to that even if I choose one of the wrong "doors" instead of simply ending the console. So how do I execute a particular block of code from within an If...Then...ElseIf...Else statement? And if for instance, I wanted each of those choices to lead to another block of code with another choice instead of ending the console with "Death" how would I acheive that?
@MilesWilliams: Ahh yes ... reminds me of my first text-based adventure I wrote in BASIC on the Commodore 64 ... fun times.
I hope you don't mind if I took the ball and ran with it.
https://gist.github.com/anonymous/7856d78bed1b6e138011
I demo a few things here:
(1) I answered your exact question. I broke the choices into Sub methods. By doing so, I can manage what happens next without if statements embedded in if statements embedded in if statements.
(2) I also added a loop at the very beginning. This allows the player to play again and try different options.
(3) I added another option after the Green Door scenario ... this is a demo of how you would continue to add to the story and further branch. Ultimately, you'll need some naming convention ... or method of organizing the Subs. You could even use a bunch of additional Module .vb files to accomplish this.
Having said all of that, I probably wouldn't write this application quite this way. I might take a more Object Oriented approach. You'll learn about that later in this series. Hopefully this will allow you to experiment more and see another way to "solve" this dilemma. Like I said earlier, this is exactly how I learned ... I created a text-based adventure based on Dungeons & Dragons which I was really into as a kid. Good luck!!!
@BobTabor:
Wow! Thank you for the extremely swift reply Bob.
After my OP I thought about it some more and was wondering if the GoTo command would be a viable option?
But after seeing what you have done I guess that would probably make a mess of things, someone once told me to keep away from using the GoTo command too much.
I thought a text based adventure would probably be the easiest way to get accustomed to writing in VB. And yeah i too played D&D as a kid. Good times.
I was hoping to use a bunch of Module.vb's as you suggested as well as txt files that stored data that i could pull in and out of the code but was unsure how to go about this or if it would even work. Not sure if using the txt files is neccessary though. I just thought it would be easier to modify things if I just had to open a txt and change some values instead of sifting through code to find them.
I will continue watching the videos and hopefully by the end I will have some more ideas.. I just watched the one on dates and timespan and thought of a good idea for random encounters to be generated after a certain amount of time has passed within a certain "area" of the game.. Also setting a real-time to game-time ratio that makes your character "age" as well.. But for now I just need to focus on making the player move throughout the code. Next I want to be able to assign "stats" and "attributes" to the player and work on a combat system with a random number generator that is modified by these factors. And also certain player choices would be affected by them.. I know it will take a while to figure all this out but I am determined.
Again, thank you for the swift reply and the tremendously helpful answers. I havn't had the time to try it out yet but once I do I am sure I will have more questions..
Fabulous video series, excellent job. Fantastic teacher! Love your work Bob!
Oh by the way , I love the entrance of the "strange little man" too funny!
**edit**
I am guessing the ToLower is so that the players input is not case sensitive?
Also am guessing that using the Call command is better than a GoTo as it calls up another Sub Procedure instead of just moving to a particular line of code, obviously there are other reasons behind this choice?
@BobTabor:
There is one thing that I am curious on though Bob? At the start it asks for your name, then proceeds to the Call command and moves to that particular Sub being referenced. Upon "death" and the Call command having run its course does it simply go back to the next line of code in Sub Main after the initial Call command was executed? Is this where a GoTo would come in handy, if I for instance had other code after the initial Call command that I wanted to skip past? Naming a line further down in the code and moving to that with GoTo instead? I am trying to understand where a GoTo would be useful as it seems like it could be a handy tool but I have been frightened away from it from a work colleague (who codes in C and Delphi but knows a bit of VB)
@MilesWilliams: Generally, I never recommend a GOTO ... I would instead labor to allow code to return or "fall out" of the Subs, kind of like what I demonstrated in the code examples. Does that make sense?
i having trouble with if then else
i really don't know how to do a several if them else.
example: input, "enter your age:" 16.
display, can you drive "yes"
display, "you won a car"
and if you enter a different number
example: input, "enter your age:" 10.
display, can you drive "no"
display, "sorry to young"
@david jones: You would simply embed one if then INSIDE of another if then. See below how I embed one inside of another (first case):
Console.WriteLine("How old are you?") Dim ageAnswer as String ageAnswer = Console.ReadLine() Dim age as Integer age = CInt(ageAnswer) If age => 16 Then Dim driveAnswer as String Console.WriteLine("Can you drive a car (type: yes or no)?") driveAnswer = Console.ReadLine() If driveAnswer = "yes" Then Console.WriteLine("You must be able to drive to win a car") End If Else Console.WriteLine("You are too young to drive a car") End If Console.ReadLine()Note: My code doesn't match yours exactly because if you're younger than 10, it's irrelevant whether or not you can drive ... you're too young regardless! I know this is a silly example ... if you needed to, you could perform another If Then in there, too. And even another one inside of that!
At some point, if you were to embed several layers deep, you should ask yourself if there's a better way to do what you want. That might get confusing and hard to read. I would switch out to using methods / functions / subs at that point. Good luck!
Remove this comment
Remove this thread
close