473,322 Members | 1,911 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,322 software developers and data experts.

Another question on loops...

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

Dec 21 '05 #1
5 1283
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


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

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

--
Sent via .NET Newsgroups
http://www.dotnetnewsgroups.com
Dec 22 '05 #3
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/de...tchFinally.asp
Hope this helps, let me know!
chrisj

"Howard" <ho**********@gmail.com> wrote in message
news:OF**************@TK2MSFTNGP14.phx.gbl...
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

--
Sent via .NET Newsgroups
http://www.dotnetnewsgroups.com


Dec 22 '05 #4
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

--
Sent via .NET Newsgroups
http://www.dotnetnewsgroups.com
Dec 22 '05 #5
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

"Howard" <ho**********@gmail.com> wrote in message
news:OG**************@TK2MSFTNGP10.phx.gbl...
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

--
Sent via .NET Newsgroups
http://www.dotnetnewsgroups.com

Dec 22 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Oleg Leschov | last post by:
Could there be means of exiting nested loops in python? something similar to labelled loops in perl.. I consider it irrating to have to make a flag for sole purpose of checking it after loop if...
15
by: JustSomeGuy | last post by:
I have a need to make an applicaiton that uses a variable number of nested for loops. for now I'm using a fixed number: for (z=0; z < Z; ++z) for (y=0; y < Y; ++y) for (x=0; x < X; ++x)
46
by: Neptune | last post by:
Hello. I am working my way through Zhang's "Teach yourself C in 24 hrs (2e)" (Sam's series), and for nested loops, he writes (p116) "It's often necessary to create a loop even when you are...
6
by: Scott Brady Drummonds | last post by:
Hi, everyone, I was in a code review a couple of days ago and noticed one of my coworkers never used for() loops. Instead, he would use while() loops such as the following: i = 0; while (i...
15
by: MuZZy | last post by:
Hi, Consider this: ArrayList al = new ArrayList(); FillList(al); /// NOW TWO SCENARIOS: /// 1. for (int i = 0 ; i < al.Count ; i++)
17
by: John Salerno | last post by:
I'm reading Text Processing in Python right now and I came across a comment that is helping me to see for loops in a new light. I think because I'm used to the C-style for loop where you create a...
10
by: Putty | last post by:
In C and C++ and Java, the 'for' statement is a shortcut to make very concise loops. In python, 'for' iterates over elements in a sequence. Is there a way to do this in python that's more concise...
2
by: bitong | last post by:
I'm a little bit confuse with regard to our subject in C..We are now with the Loops..and I was just wondering if given a problem, can you use Do-while loops instead of a for loops or vise versa? are...
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...
43
by: Adem24 | last post by:
The World Joint Programming Language Standardization Committe (WJPLSC) hereby proclaims to the people of the world that a new programming language is needed for the benefit of the whole mankind in...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....

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.