Entries:
Comments:
Posts:

Loading User Information from Channel 9

Something went wrong getting user information from Channel 9

Latest Achievement:

Loading User Information from MSDN

Something went wrong getting user information from MSDN

Visual Studio Achievements

Latest Achievement:

Loading Visual Studio Achievements

Something went wrong getting the Visual Studio Achievements

Branching with the If . . . Then . . . Else Decision Statement - 06

Download

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.

 

Download the source code for Branching with the If...

Tag:

Follow the Discussion

  • Very cool love the example in the end.  Never knew about the {0} and the iif, really cool!

  • JoeJoe

    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.)

  • halitateshalitates

    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?

  • KenKen

    This lesson is very informative. Loved it! Thanks.

  • Austin EnosAustin Enos

    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.

  • Jag mohanJag mohan

    @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.  Smiley  Please write me directly ... bob at learn visual studio dot net and I'll try to help if I can.  Best wishes!

  • GinnyGinny

    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.

  • GinnyGinny

    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.

  • GinnyGinny

    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.  Smiley  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.

  • Golnazgolnazal HEY HEY HEY

    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.   Devil

    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?

  • david jonesdavid jones

    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!

  • Zach EhretZach Ehret

    Hey Bob You may have answered this already I looked and didn't see anything can you help me with this code? I just started.
    --
    Module Module1

    Sub Main()
    Console.WriteLine("What is your choice?")
    Console.WriteLine("Rock (1)")
    Console.WriteLine("Paper (2)")
    Console.WriteLine("Scissors (3)")
    Console.ReadLine()
    Dim uservalue As String = Console.ReadLine()
    Dim message As String
    uservalue = Console.ReadLine()

    If uservalue = "1" Then
    message = "You Selected Rock"
    ElseIf uservalue = "2" Then
    message = "You Selected Paper"
    Console.WriteLine("You selected Paper")
    ElseIf uservalue = "3" Then
    message = "You Selected Scissors"
    Else
    message = "The input you entered was invalid, you automatically lose! :("
    End If
    Console.WriteLine(message)
    Console.ReadLine()
    End Sub

    End Module
    --

  • @Zach Ehret: Hi Zach, I need more information ... what are you trying to accomplish?  What error are you getting?  Or are you just not getting the results you expected?  Please be as descriptive as possible so I can help pinpoint the problem.  thanks!

  • Zach EhretZach Ehret

    After I watch the rest of the tutorials i plan on making a rock, paper, scissors as my first project. For example when you enter 1 it goes to the else and displays "The input you entered was invalid, you automatically lose!:(". When the program is built/compiled no error is detected.

  • Zach EhretZach Ehret

    Or when it is debugged

  • @Zach Ehret: Look at these lines of code:

    Dim uservalue As String = Console.ReadLine()
    Dim message As String
    uservalue = Console.ReadLine()

    You are calling Console.ReadLine TWICE!  The first time you are hitting the number 1 on the keyboard.  The second time you are probably hitting the Enter key on the keyboard, resulting in setting the userValue variable to an empty string.  Set a break point and validate what I said is true.  Hope that helps!

  • Zach EhretZach Ehret

    Thanks, it works now. Onto watching the rest of your tutorials!

  • Zach EhretZach Ehret

    Hey one more question how do I get my free visual studio 2012 registration code for the free version?

  • @Zach Ehret: There's a little dialog that will pop up asking you to register your copy of the tool.  It's free ... they just want to see who is using the express editions so they can justify keeping this sort of thing available for free.  If you don't see that code, take a look at the options in the Help menu ... there should be a sub-menu option to Register.  I don't have it open right now (I'm away from home at the moment) so you may need to look around a little.  Hope that helps!

  • Zach EhretZach Ehret

    Thanks got it registered

  • LiamLiam

    coming from javascript, i tend to use ("some text" + variableName) with the "+" to include the variable. are "&" and "+" equivalent?

  • @Liam: Yes.  There might be some small nuanced differences, but for the most part, in VB the & is the string concatenation operator.  Smiley

  • LeeLee

    Hi Bob,

    This is a small thing, and I can't see any difference in the code, so I'm wondering if its simply a difference in versions.

    When the console/command window pops up and you enter 1,2 or 3, on mine it does not show as on the next line. The cursor is right next to the question mark and that's where you have to type the answer. Other than that it works perfectly! :D

    Loving the videos - I'm deaf, so it's great that you have your face visible for large portions, and you speak very clearly. It really helps!!

  • @Lee: Hi Lee, I might have an extra Console.WriteLine() in there I'm guessing.  Otherwise, I can't imagine why that would happen.  But I would say this ... we're learning the Visual Basic language ... you probably won't be writing many Console style applications in real life ... unless you're an old school Zork enthusiast.  Smiley

    Also, I think Channel9 is working on captions this year, so that should help even further.  Thanks for the kind words, and best wishes as you continue through this series!

  • AkashAkash

    You do not know how much I love you and your videos man! So helpful!! Thank you VERY much!

  • @Akash: HAHA!  Thanks Akash.  Smiley

Remove this comment

Remove this thread

close

Comments Closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums,
or Contact Us and let us know.