While Loops (I think)...

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Howard

    While Loops (I think)...

    Hello everyone (total VB.NET beginner here),
    I'm reading the "SAMS Teach Yourself VB.NET In 21 Days" book, and came
    across an exercise that I can't get to work. The exercise asks that
    you create a game that makes the user guess a number from 1-100, and
    you tell the user "lower" or "higher" as they input their guesses,
    until they guess the correct number, at which point you then tell the
    user "Correct". I tried using the While Loop, and it "sort of" worked,
    but after a while (no pun intended) of inputting numbers (guesses), it
    said "Correct" to incorrect answers.

    The chapter was discussing different types of loops among other things,
    and I'm guessing that they want us to use a While Loop for this
    exercise. If anyone has the book, it's at the end of day two (page
    101).

    Please let me know of any suggestions you may have.

    Thank you very much.
    Howard

  • Herfried K. Wagner [MVP]

    #2
    Re: While Loops (I think)...

    Hi Howard,

    "Howard" <hollywoodhow@g mail.com> schrieb:[color=blue]
    > I'm reading the "SAMS Teach Yourself VB.NET In 21 Days" book, and came
    > across an exercise that I can't get to work. The exercise asks that
    > you create a game that makes the user guess a number from 1-100, and
    > you tell the user "lower" or "higher" as they input their guesses,
    > until they guess the correct number, at which point you then tell the
    > user "Correct". I tried using the While Loop, and it "sort of" worked,
    > but after a while (no pun intended) of inputting numbers (guesses), it
    > said "Correct" to incorrect answers.
    >
    > The chapter was discussing different types of loops among other things,
    > and I'm guessing that they want us to use a While Loop for this
    > exercise. If anyone has the book, it's at the end of day two (page
    > 101).[/color]

    I do not have the book, but you could post relevant parts of your code here
    to enable other people to see where the problem lies.

    --
    M S Herfried K. Wagner
    M V P <URL:http://dotnet.mvps.org/>
    V B <URL:http://classicvb.org/petition/>

    Comment

    • Howard Portney

      #3
      Re: While Loops (I think)...

      Thank you for the help,
      Here's the code that I used in an attempt to make the exercise render:

      Module Module1

      Sub Main()
      Console.WriteLi ne("Pick a number from 1 to 100")
      Dim StrInput As Integer = Console.ReadLin e()

      While (StrInput < "27")
      Console.WriteLi ne("higher")
      StrInput = Console.ReadLin e()
      End While
      While (StrInput > "27")
      Console.WriteLi ne("lower")
      StrInput = Console.ReadLin e()
      End While
      Console.WriteLi ne("Correct!")
      StrInput = Console.ReadLin e()

      End Sub

      End Module

      Thanks again,
      Howard

      *** Sent via Developersdex http://www.developersdex.com ***

      Comment

      • Joseph Bittman MVP MCSD

        #4
        Re: While Loops (I think)...

        December 18, 2005

        Hi Howard, the issue is the way the code is set up. As soon as you enter a
        value higher than 27, it moves down to While StrInput > 27, and therefore is
        never checked again if it is lower than 27.... so if you input any value
        lower than 27 after it moves to checking whether the value is higher, then
        you will move past the 2nd while and get the Correct message.

        To demonstrate:
        -Reach Correct in 2 incorrect values:
        input 28+
        input less than 27
        CORRECT! :) lol

        What you need to do is check whether it is lower/higher/correct EACH time a
        value is inputed, not just check once and if it passes then never check the
        new values.

        This can be accomplished by using a While Incorrect(as boolean) type
        structure:

        Dim SuccessfulGuess as boolean = false
        Dim StrInput as integer

        While SuccessfulGuess = false

        StrInput = Console.Readlin e

        if StrInput < 27 then
        console.writeli ne("higher")

        ElseIf StrInput > 27 then
        console.writeli ne("lower")

        ElseIf StrInput = 27
        console.writeli ne("Correct!")
        SuccessfulGuess = true
        End If

        end while


        Let me know if you have questions! :-)

        --

        Joseph Bittman
        Microsoft Certified Solution Developer
        Microsoft Most Valuable Professional -- DPM

        Blog/Web Site: http://71.39.42.23/



        "Howard Portney" <hollywoodhow@g mail.com> wrote in message
        news:OBt9AdDBGH A.3760@tk2msftn gp13.phx.gbl...[color=blue]
        > Thank you for the help,
        > Here's the code that I used in an attempt to make the exercise render:
        >
        > Module Module1
        >
        > Sub Main()
        > Console.WriteLi ne("Pick a number from 1 to 100")
        > Dim StrInput As Integer = Console.ReadLin e()
        >
        > While (StrInput < "27")
        > Console.WriteLi ne("higher")
        > StrInput = Console.ReadLin e()
        > End While
        > While (StrInput > "27")
        > Console.WriteLi ne("lower")
        > StrInput = Console.ReadLin e()
        > End While
        > Console.WriteLi ne("Correct!")
        > StrInput = Console.ReadLin e()
        >
        > End Sub
        >
        > End Module
        >
        > Thanks again,
        > Howard
        >
        > *** Sent via Developersdex http://www.developersdex.com ***[/color]


        Comment

        • _AnonCoward

          #5
          Re: While Loops (I think)...


          "Howard Portney" <hollywoodhow@g mail.com> wrote in message
          news:OBt9AdDBGH A.3760@tk2msftn gp13.phx.gbl...
          :
          : Thank you for the help,
          : Here's the code that I used in an attempt to make the exercise render:
          :
          : Module Module1
          :
          : Sub Main()
          : Console.WriteLi ne("Pick a number from 1 to 100")
          : Dim StrInput As Integer = Console.ReadLin e()
          :
          : While (StrInput < "27")
          : Console.WriteLi ne("higher")
          : StrInput = Console.ReadLin e()
          : End While
          : While (StrInput > "27")
          : Console.WriteLi ne("lower")
          : StrInput = Console.ReadLin e()
          : End While
          : Console.WriteLi ne("Correct!")
          : StrInput = Console.ReadLin e()
          :
          : End Sub
          :
          : End Module
          :
          : Thanks again,
          : Howard
          :
          : *** Sent via Developersdex http://www.developersdex.com ***


          Here's another variation:

          Option Strict

          Imports Microsoft.Visua lBasic
          Imports System

          Public Module [module]
          Public Sub Main

          Dim Done As Boolean = False
          Console.WriteLi ne("Pick a number from 1 to 100 " & _
          "(or ""exit"" to end)")

          Do Until Done
          Dim StrInput As String = Console.ReadLin e

          If lcase(strInput) = "exit" Then
          Done = True
          ElseIf Not IsNumeric(strIn put) Then
          Console.WriteLi ne("I'm sorry, but """ & strInput & _
          """ is not a number. Please try again.")
          Else
          Select Case CInt(strInput)
          Case Is < 27
          Console.WriteLi ne("Higher..")
          Case Is > 27
          Console.WriteLi ne("Lower...")
          Case Else
          Console.WriteLi ne("Correct!")
          Done = True
          End Select
          End If
          Loop
          End Sub
          End Module


          Ralf
          --
          --
          ----------------------------------------------------------
          * ^~^ ^~^ *
          * _ {~ ~} {~ ~} _ *
          * /_``>*< >*<''_\ *
          * (\--_)++) (++(_--/) *
          ----------------------------------------------------------
          There are no advanced students in Aikido - there are only
          competent beginners. There are no advanced techniques -
          only the correct application of basic principles.




          Comment

          • Howard Portney

            #6
            Re: While Loops (I think)...

            Hi Joseph, and thank you so much for the help. The code that you sent
            me worked perfectly.
            I'm not sure however, if I understand the explanation of why my While
            Loops didn't work properly.
            Was it because once the user enters a value GREATER than 27, and then
            enters any values LOWER than 27 - the {While StrInput > 27} loop is no
            longer checked? And vica-versa with the While StrInput < 27 loop? As
            you can tell, I'm really new at this! LOL!

            I just want to make sure that I have a grip on this before I move onto
            the next chapter.

            Thanks again,
            Howard

            *** Sent via Developersdex http://www.developersdex.com ***

            Comment

            • Herfried K. Wagner [MVP]

              #7
              Re: While Loops (I think)...

              Howard Portney wrote:[color=blue]
              > Was it because once the user enters a value GREATER than 27, and then
              > enters any values LOWER than 27 - the {While StrInput > 27} loop is no
              > longer checked?[/color]

              Yes. The first 'While' loop will exit when the first number >= 27 is
              entered by the user. Then the second 'While' loop is executed as long
              as a number <= 27 is entered. Program flow is from top to bottom.

              --
              Herfried K. Wagner [MVP]
              <URL:http://dotnet.mvps.org/>

              Comment

              • Cor Ligthert [MVP]

                #8
                Re: While Loops (I think)...

                Herfried,

                I had expected here something about the Do While or the Do Until

                Refering to a short time in past (correct) correction on a message from you
                to me and the discussion what was after that.

                :-)

                Cor

                "Herfried K. Wagner [MVP]" <hirf-spam-me-here@gmx.at> schreef in bericht
                news:eTCpD4HBGH A.2708@TK2MSFTN GP12.phx.gbl...[color=blue]
                > Howard Portney wrote:[color=green]
                >> Was it because once the user enters a value GREATER than 27, and then
                >> enters any values LOWER than 27 - the {While StrInput > 27} loop is no
                >> longer checked?[/color]
                >
                > Yes. The first 'While' loop will exit when the first number >= 27 is
                > entered by the user. Then the second 'While' loop is executed as long as
                > a number <= 27 is entered. Program flow is from top to bottom.
                >
                > --
                > Herfried K. Wagner [MVP]
                > <URL:http://dotnet.mvps.org/>[/color]


                Comment

                • Howard

                  #9
                  Re: While Loops (I think)...

                  Thank you very much everyone.

                  Howard

                  Comment

                  • Branco Medeiros

                    #10
                    Re: While Loops (I think)...

                    Howard wrote:[color=blue]
                    > Hello everyone (total VB.NET beginner here),
                    > I'm reading the "SAMS Teach Yourself VB.NET In 21 Days" book, and came
                    > across an exercise that I can't get to work. The exercise asks that
                    > you create a game that makes the user guess a number from 1-100, and
                    > you tell the user "lower" or "higher" as they input their guesses,
                    > until they guess the correct number, at which point you then tell the
                    > user "Correct". I tried using the While Loop, and it "sort of" worked,
                    > but after a while (no pun intended) of inputting numbers (guesses), it
                    > said "Correct" to incorrect answers.[/color]
                    <snip>

                    and then sent some code:

                    <snip>[color=blue]
                    > Sub Main()
                    > Console.WriteLi ne("Pick a number from 1 to 100")
                    > Dim StrInput As Integer = Console.ReadLin e()
                    >
                    > While (StrInput < "27")
                    > Console.WriteLi ne("higher")
                    > StrInput = Console.ReadLin e()
                    > End While
                    > While (StrInput > "27")
                    > Console.WriteLi ne("lower")
                    > StrInput = Console.ReadLin e()
                    > End While
                    > Console.WriteLi ne("Correct!")
                    > StrInput = Console.ReadLin e()
                    >
                    > End Sub[/color]
                    <snip>

                    The While loop will execute until a given condition becomes true. Its
                    structure is:

                    While Condition
                    'Do something
                    End While

                    where Condition represents a boolean expression.

                    In your case, the condition that "governs" the loop is the number
                    entered being diferent from a given value: Number <> Value.

                    Therefore, your While loop would look like this:

                    While Number <> Value

                    'Do something

                    End While

                    If the condition ceases to be true then the looping will stop and
                    execution will proceed at the next instruction.

                    In your case this will happen only when Number ceases to be different
                    from Value. In other words, when execution breaks out of the loop, we
                    know we have a Number which is equal to Value and therefore we may do
                    something about it, which is to congratulate the user and finish the
                    program:

                    While Number <> Value

                    'Do something

                    End While
                    Console.WriteLi ne("Correct!")

                    Now, back to the While loop. What to do while Number remains different
                    from Value? The problem states that we must print "lower" if Number is
                    above Value, or "higher" if Number is bellow Value:

                    While Number <> Value

                    If Number < Value Then
                    Console.WriteLi ne("Higher")
                    Else
                    'the number can only be above the value
                    Console.WriteLi ne("Lower")
                    End If

                    End While
                    Console.WriteLi ne("Correct!")

                    Of course, there are still a few parts missing. Notice that a common
                    use-pattern of the While loop goes like this:

                    Get some input
                    While the input is not valid
                    Show some message
                    Get the input again
                    (end While)
                    Deal with the valid input

                    In your case, this might translate to the following actions:

                    'Get some input
                    Console.WriteLi ne("Pick a number from 1 to 100")
                    Number = Integer.Parse(C onsole.ReadLine ())

                    'While the Input is not valid
                    While Number <> Value

                    'Show some message
                    If Number < Value Then
                    Console.WriteLi ne("Higher")
                    Else
                    Console.WriteLi ne("Lower")
                    End If

                    'Get the input again
                    Number = Integer.Parse(C onsole.ReadLine ())

                    End While

                    'Deal with the valid input
                    Console.WriteLi ne("Correct!")

                    Of course, in a correct VB.Net app we need to define variable types and
                    constants. Therefore, the full program would be:

                    Sub Main()
                    Const Value As Integer = 27
                    Dim Number As Integer

                    Console.WriteLi ne("Pick a number from 1 to 100")
                    Number = Integer.Parse(C onsole.ReadLine ())

                    While Number <> Value
                    If Number < Value Then
                    Console.WriteLi ne("Higher")
                    Else
                    Console.WriteLi ne("Lower")
                    End If
                    Number = Integer.Parse(C onsole.ReadLine ())
                    End While

                    Console.WriteLi ne("Correct!")
                    End Sub

                    HTH.

                    Regards,

                    Branco.

                    Comment

                    • Howard Portney

                      #11
                      Re: While Loops (I think)...

                      Branco,
                      Thank you so much! That was such an excellent written discussion of how
                      the progam works step by step. In fact, it was even better than the
                      book! That helped me tremendously.

                      Thanks again,
                      Howard

                      *** Sent via Developersdex http://www.developersdex.com ***

                      Comment

                      • Howard

                        #12
                        Re: While Loops (I think)...

                        Ok, I'm back. I have another question (probably an easy one, even to
                        non-experts). I was inspired to add some more to this little program
                        (thanks to all of your help). If I was using the following code to
                        create a game that prompts the user to guess a number from 1-100, and
                        wanted to have the console write a message Console.WriteLi ne("Invalid
                        Entry") when the user types in character(s) that are non-numerical -
                        What would the syntax be for this? Here's the code (which works great)
                        but without that new part.

                        Module Module1

                        Sub Main()
                        Const Value As Integer = 27
                        Dim Number As Integer

                        Console.WriteLi ne("Pick a number from 1 to 100")
                        Number = Integer.Parse(C onsole.ReadLine ())

                        While Number <> Value
                        If Number < Value Then
                        Console.WriteLi ne("Higher")
                        Else
                        Console.WriteLi ne("Lower")
                        End If
                        Number = Integer.Parse(C onsole.ReadLine ())
                        End While

                        Console.WriteLi ne("Correct!")
                        End Sub

                        End Module

                        Thank you,
                        Howard Portney

                        Comment

                        • Chris Johnson

                          #13
                          Re: While Loops (I think)...

                          Howard, you actually have much of the logic in place to do this, in that
                          currently if your user enters a non-numeric, your program would error.

                          Below, you will see some come to trap that error, and give them up to
                          two more chances to get it right. I included the multiple tries thing incase
                          you wanted to experiement a little more with the power of structured error
                          handling ("Try..Catch... Finally")


                          Module Module1
                          Sub Main()
                          Dim iAttempts As Integer = 0
                          Do
                          Try
                          Const Value As Integer = 27
                          Dim Number As Integer

                          Console.WriteLi ne("Pick a number from 1 to 100")
                          Number = Integer.Parse(C onsole.ReadLine ())

                          While Number <> Value
                          If Number < Value Then
                          Console.WriteLi ne("Higher")
                          Else
                          Console.WriteLi ne("Lower")
                          End If
                          Number = Integer.Parse(C onsole.ReadLine ())
                          End While
                          Console.WriteLi ne("Correct!")
                          Catch strEx1 As Exception When iAttempts < 3
                          iAttempts += 1
                          Console.WriteLi ne(strEx1.Messa ge)
                          Catch strEx2 As Exception
                          Console.WriteLi ne("You have entered an incompatable value 3
                          times, or encountered a more serious error. The program will now exit.")
                          Exit Do
                          End Try
                          Loop
                          End Sub
                          End Module



                          Please feel free to ask if you have more questions,
                          chrisj




                          "Howard" <hollywoodhow@g mail.com> wrote in message
                          news:1135136740 .164821.155300@ g49g2000cwa.goo glegroups.com.. .[color=blue]
                          > Ok, I'm back. I have another question (probably an easy one, even to
                          > non-experts). I was inspired to add some more to this little program
                          > (thanks to all of your help). If I was using the following code to
                          > create a game that prompts the user to guess a number from 1-100, and
                          > wanted to have the console write a message Console.WriteLi ne("Invalid
                          > Entry") when the user types in character(s) that are non-numerical -
                          > What would the syntax be for this? Here's the code (which works great)
                          > but without that new part.
                          >
                          > Module Module1
                          >
                          > Sub Main()
                          > Const Value As Integer = 27
                          > Dim Number As Integer
                          >
                          > Console.WriteLi ne("Pick a number from 1 to 100")
                          > Number = Integer.Parse(C onsole.ReadLine ())
                          >
                          > While Number <> Value
                          > If Number < Value Then
                          > Console.WriteLi ne("Higher")
                          > Else
                          > Console.WriteLi ne("Lower")
                          > End If
                          > Number = Integer.Parse(C onsole.ReadLine ())
                          > End While
                          >
                          > Console.WriteLi ne("Correct!")
                          > End Sub
                          >
                          > End Module
                          >
                          > Thank you,
                          > Howard Portney
                          >[/color]


                          Comment

                          Working...