473,569 Members | 2,463 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.WriteLi ne("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.WriteLi ne("Pick a number from 1 to 100")
Number = Integer.Parse(C onsole.ReadLine ())

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

Console.WriteLi ne("Correct!")
End Sub

End Module

Thank you,
Howard

Dec 21 '05 #1
5 1296
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.WriteLi ne("Pick a number from 1 to 100")
Number = Integer.Parse(C onsole.ReadLine ())

While Number <> Value
If Number < Value Then
Console.WriteLi ne("Higher")
Else
Console.WriteLi ne("Lower")
End If
Number = Integer.Parse(C onsole.ReadLine ())
End While
Console.WriteLi ne("Correct!")
Catch strEx1 As Exception When iAttempts < 3
iAttempts += 1
Console.WriteLi ne(strEx1.Messa ge)
Catch strEx2 As Exception
Console.WriteLi ne("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**********@g mail.com> wrote in message
news:11******** **************@ g14g2000cwa.goo glegroups.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.WriteLi ne("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.WriteLi ne("Pick a number from 1 to 100")
Number = Integer.Parse(C onsole.ReadLine ())

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

Console.WriteLi ne("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..Fin ally..End Try,
check this page out:
http://msdn.microsoft.com/library/de...tchFinally.asp
Hope this helps, let me know!
chrisj

"Howard" <ho**********@g mail.com> wrote in message
news:OF******** ******@TK2MSFTN GP14.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.WriteLi ne("Pick a number from 1 to 100")
Number = Integer.Parse(C onsole.ReadLine ())

While Number <> Value
If Number < Value Then
Console.WriteLi ne("Higher")
Else
Console.WriteLi ne("Lower")
End If
Number = Integer.Parse(C onsole.ReadLine ())
End While
Console.WriteLi ne("Correct!")
Catch strEx1 As Exception When iAttempts < 3
iAttempts += 1
Console.WriteLi ne(strEx1.Messa ge)
Catch strEx2 As Exception
Console.WriteLi ne("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.ReadLin e (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.WriteLi ne("You have entered an incompatable... ")
Console.ReadKey ()
Exit Do
End Try

Hope that helps!
chrisj

"Howard" <ho**********@g mail.com> wrote in message
news:OG******** ******@TK2MSFTN GP10.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.WriteLi ne("Pick a number from 1 to 100")
Number = Integer.Parse(C onsole.ReadLine ())

While Number <> Value
If Number < Value Then
Console.WriteLi ne("Higher")
Else
Console.WriteLi ne("Lower")
End If
Number = Integer.Parse(C onsole.ReadLine ())
End While
Console.WriteLi ne("Correct!")
Catch strEx1 As Exception When iAttempts < 3
iAttempts += 1
Console.WriteLi ne(strEx1.Messa ge)
Catch strEx2 As Exception
Console.WriteLi ne("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
5106
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 we need to break once more... So maybe there should be an argument to break that is an int which is a number of loops to break. So it would...
15
6567
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
9884
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 already in a loop." Then he goes on to portray a contrived example that doesn't tell me under what conditions a nested loop might be favoured as a...
6
1703
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 < n) { ...
15
1349
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
3038
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 counter within the loop declaration, for loops have always seemed to me to be about doing something a certain number of times, and not about...
10
3959
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 than 'while'? C: for(i=0; i<length; i++) python: while i < length:
2
2289
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 there instances that you must use a Do-while loops instead of a for loops or a while loop? or you can use any types of loops in any given problem?
3
2400
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 field they are fairly large. the net result is that when 60 or so results are reitreved the page size is 400kb! which takes too long to load. is...
43
3640
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 the 21st millenium. This new language not only differs from existing ones by new features and paradigms but which also brings real advantage by...
0
8132
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7678
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7982
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5514
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5222
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3644
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2116
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1226
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
944
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.