473,386 Members | 1,803 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

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
12 1954
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Paul Charlton-Thomson | last post by:
Hi, I am trying to execute 2 queries and then output the results in 2 loops but maybe I'm using the wrong approach. Can anyone help me here ... $query_1 = "SELECT field_1 FROM table_1";...
6
by: kydavis77 | last post by:
i was wondering if anyone could point me to some good reading about the for and while loops i am trying to write some programs "Exercise 1 Write a program that continually reads in numbers...
3
by: monomaniac21 | last post by:
hi all i have a script that retrieves rows from a single table, rows are related to eachother and are retrieved by doing a series of while loops within while loops. bcos each row contains a text...
5
by: Alex | last post by:
Hi I just want to clear something up in my head with while loops and exceptions. I'm sure this will probably be a no brainer for most. Check this simple pseudo-code out (vb.net): ...
1
by: jiggaman828 | last post by:
Am I doing something wrong with setting my width? I thought I had it correct. Can any inform me on how to write 4 different while or do-while loops counting down to 0, it has to be lined up column...
4
by: danbuttercup | last post by:
Hi everyone I just recently learnt how to do while loops in my java class and I am completely lost. I have to make programs for the following questions but I have no idea were to start. ...
1
by: Wazza | last post by:
G'Day, I have a re-occurring problem and wish to design a framework or pattern to address it. I have some Ideas but I would like to do some brainstorming with my peers before commencing. The...
8
by: blazzer | last post by:
Hi, I'm beginner at Java. I'm confused with my simple program of using while loops int i = 1; while (i <= input){ System.out.println("Enter description of product #" + i + "...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.