Another question on loops...

H

Howard

Ok, I'm back. I have another question (probably an easy one, even to
non-experts). I was inspired to expand 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
 
C

Chris Johnson

Howard, I saw your message in the VB6 group as well, you might try
to avoid the confusion in the future and just post your message in the
..NET group if its .NET related.

But on to the point, 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
 
H

Howard

Thanks Chris,
I was wondering if you can explain a little bit on the newly added code.
I think I understand it, but not 100% positive on it.

Thanks again,
Howard
 
C

Chris Johnson

Howard, no problem at all. I've commented about a few lines below that I
thought would be the best for you, please let me know if you have any
other questions after these.


Dim iAttempts As Integer = 0
'iAttempts is simple a integer variable I plan to use to track the
'number of times the user has entered an invalid variable.

Do
'This part might be tricky, the Do...Loop encompasses everything
'the program does. This is necessary because when an invalid value
'is entered the program will fall to to the Catch, and then normally
'would fall to the end sub. In this setup, it will Loop back to the
top
'and ask the user for the value again.

Try
'Literally, all of the code we want to "try" and execute.

Catch strEx1 As Exception When iAttempts < 3
'Catch is new to VB and a great tool. You can have multiple catches
'in a program based on what types of execeptions you want to trap,
'or just a generic catch like this one. This catch tell the program
to
'execute the contained code when any exception is raised and when
'iAttempts is less than 3.

iAttempts += 1
'Since we are in the catch, an invalid value was obviously
'entered. We must increment iAttempts or risk an infinite loop.

Catch strEx2 As Exception
'This will catch all other errors, to include an invalid character
when
'iAttempts is greater than 4.

Exit Do
'This ensures if the program encounters an exception, or if it
'encounters the fourth invalid charactor.

End Try
'Required to close out the Try...Catch

Loop
'This is the loop to ensure continuance, as discussed above.


For more information in the abilities of the Try..Catch..Finally..End Try,
check this page out:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vblr7/html/vastmTryCatchFinally.asp


Hope this helps, let me know!
chrisj
 
H

Howard

Chris,
First let me start by saying that your explanation was excellent! Thank
you so much. I ran the following code, which worked great, but after
inputting four invalid characters (intentionally), the console closed so
fast that I couldn't get a chance to see what was displayed. Is there a
way to prevent that from happening?

Here's the code you gave me thus far:

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

Thanks again,
Howard
 
C

Chris Johnson

Howard,
Glad to hear you were able to benefit from the explanation there, I think
you will find in your ongoing projects that Try..Catch is a great friend.

As for making the program wait before closing, this is also a element
you already have in the program, just that you are using in a little
differnt
manner. When you want the program to wait for the user to enter their
value, you use the code Console.ReadLine (i.e., wait for the enter key).

To implement a wait at the end of the program that will exit when the
user presses any key, add a Console.ReadKey() to the strEx2 catch.

Resulting in:

Catch strEx2 As Exception
Console.WriteLine("You have entered an incompatable...")
Console.ReadKey()
Exit Do
End Try

Hope that helps!
chrisj
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Loops Question 3
console app command line args 3
Read XML from a File Using VB.net 5
Recursive Registry Loop 3
FindWindow is not working 2
Help With ICloneable And Deep Copy 5
Inheritance 7
Data Logger 1

Top