Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / Languages / VB.NET / December 2005

Tip: Looking for answers? Try searching our database.

While Loops (I think)...

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
Howard - 18 Dec 2005 22:58 GMT
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] - 18 Dec 2005 23:04 GMT
Hi Howard,

"Howard" <hollywoodhow@gmail.com> schrieb:
> 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
[quoted text clipped - 9 lines]
> exercise.  If anyone has the book, it's at the end of day two (page
> 101).

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.

Signature

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

Howard Portney - 19 Dec 2005 00:57 GMT
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.WriteLine("Pick a number from 1 to 100")
       Dim StrInput As Integer = Console.ReadLine()

       While (StrInput < "27")
           Console.WriteLine("higher")
           StrInput = Console.ReadLine()
       End While
       While (StrInput > "27")
           Console.WriteLine("lower")
           StrInput = Console.ReadLine()
       End While
       Console.WriteLine("Correct!")
       StrInput = Console.ReadLine()

   End Sub

End Module

Thanks again,
Howard
Joseph Bittman MVP MCSD - 19 Dec 2005 01:24 GMT
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.Readline

   if StrInput < 27 then
       console.writeline("higher")

   ElseIf StrInput > 27 then
       console.writeline("lower")

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

end while

Let me know if you have questions! :-)

Signature

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

Blog/Web Site: http://71.39.42.23/

> Thank you for the help,
> Here's the code that I used in an attempt to make the exercise render:
[quoted text clipped - 24 lines]
>
> *** Sent via Developersdex http://www.developersdex.com ***
Howard Portney - 19 Dec 2005 03:56 GMT
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
Herfried K. Wagner [MVP] - 19 Dec 2005 09:24 GMT
> 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?

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.

Signature

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

Cor Ligthert [MVP] - 19 Dec 2005 09:52 GMT
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

>> 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
[quoted text clipped - 3 lines]
> 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.
Howard - 19 Dec 2005 15:17 GMT
Thank you very much everyone.

Howard
_AnonCoward - 19 Dec 2005 03:27 GMT
: Thank you for the help,
: Here's the code that I used in an attempt to make the exercise render:
[quoted text clipped - 24 lines]
:
: *** Sent via Developersdex http://www.developersdex.com ***

Here's another variation:

Option Strict

Imports Microsoft.VisualBasic
Imports System

Public Module [module]
Public Sub Main

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

 Do Until Done
   Dim StrInput As String = Console.ReadLine

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

Ralf
Signature

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

Branco Medeiros - 19 Dec 2005 20:19 GMT
> Hello everyone (total VB.NET beginner here),
> I'm reading the "SAMS Teach Yourself VB.NET In 21 Days" book, and came
[quoted text clipped - 5 lines]
> but after a while (no pun intended) of inputting numbers (guesses), it
> said "Correct" to incorrect answers.
<snip>

and then sent some code:

<snip>
>     Sub Main()
>         Console.WriteLine("Pick a number from 1 to 100")
[quoted text clipped - 12 lines]
>
>     End Sub
<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.WriteLine("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.WriteLine("Higher")
   Else
   'the number can only be above the value
     Console.WriteLine("Lower")
   End If

 End While
 Console.WriteLine("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.WriteLine("Pick a number from 1 to 100")
 Number = Integer.Parse(Console.ReadLine())

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

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

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

 End While

 'Deal with the valid input
 Console.WriteLine("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.WriteLine("Pick a number from 1 to 100")
   Number = Integer.Parse(Console.ReadLine())

   While Number <> Value
     If Number < Value Then
       Console.WriteLine("Higher")
     Else
       Console.WriteLine("Lower")
     End If
     Number = Integer.Parse(Console.ReadLine())
   End While
 
   Console.WriteLine("Correct!")
 End Sub

HTH.

Regards,

Branco.
Howard Portney - 20 Dec 2005 17:00 GMT
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
Howard - 21 Dec 2005 03:45 GMT
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.WriteLine("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.WriteLine("Pick a number from 1 to 100")
       Number = Integer.Parse(Console.ReadLine())

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

       Console.WriteLine("Correct!")
   End Sub

End Module

Thank you,
Howard Portney
Chris Johnson - 21 Dec 2005 20:37 GMT
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.WriteLine("Pick a number from 1 to 100")
               Number = Integer.Parse(Console.ReadLine())

               While Number <> Value
                   If Number < Value Then
                       Console.WriteLine("Higher")
                   Else
                       Console.WriteLine("Lower")
                   End If
                   Number = Integer.Parse(Console.ReadLine())
               End While
               Console.WriteLine("Correct!")
           Catch strEx1 As Exception When iAttempts < 3
               iAttempts += 1
               Console.WriteLine(strEx1.Message)
           Catch strEx2 As Exception
               Console.WriteLine("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

> 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
[quoted text clipped - 30 lines]
> Thank you,
> Howard Portney

Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.