467,132 Members | 1,152 Online
Bytes | Developer Community
Ask Question

Home New Posts Topics Members FAQ

Post your question to a community of 467,132 developers. It's quick & easy.

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

Dec 18 '05 #1
  • viewed: 1729
Share:
12 Replies
Hi Howard,

"Howard" <ho**********@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
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).


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/>

Dec 18 '05 #2
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

*** Sent via Developersdex http://www.developersdex.com ***
Dec 19 '05 #3
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! :-)

--

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

Blog/Web Site: http://71.39.42.23/

"Howard Portney" <ho**********@gmail.com> wrote in message
news:OB**************@tk2msftngp13.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.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

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

Dec 19 '05 #4

"Howard Portney" <ho**********@gmail.com> wrote in message
news:OB**************@tk2msftngp13.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.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
:
: *** 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
--
--
----------------------------------------------------------
* ^~^ ^~^ *
* _ {~ ~} {~ ~} _ *
* /_``>*< >*<''_\ *
* (\--_)++) (++(_--/) *
----------------------------------------------------------
There are no advanced students in Aikido - there are only
competent beginners. There are no advanced techniques -
only the correct application of basic principles.


Dec 19 '05 #5
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 ***
Dec 19 '05 #6
Howard Portney wrote:
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.

--
Herfried K. Wagner [MVP]
<URL:http://dotnet.mvps.org/>
Dec 19 '05 #7
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]" <hi***************@gmx.at> schreef in bericht
news:eT**************@TK2MSFTNGP12.phx.gbl...
Howard Portney wrote:
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.

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

Dec 19 '05 #8
Thank you very much everyone.

Howard

Dec 19 '05 #9
Howard wrote:
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. <snip>

and then sent some code:

<snip> 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

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

Dec 19 '05 #10
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 ***
Dec 20 '05 #11
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

Dec 21 '05 #12
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


"Howard" <ho**********@gmail.com> wrote in message
news:11**********************@g49g2000cwa.googlegr oups.com...
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

Dec 21 '05 #13

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

4 posts views Thread by Paul Charlton-Thomson | last post: by
6 posts views Thread by kydavis77@gmail.com | last post: by
3 posts views Thread by monomaniac21 | last post: by
5 posts views Thread by Alex | last post: by
4 posts views Thread by danbuttercup | last post: by
8 posts views Thread by blazzer | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.