Reputation: 191
I have a simple program to average ten (user-defined) numbers and then print the result. At the end of the program I'd like to print Would you like to average a new set of numbers? (Y/N)
If the user inputs y
than I want the program to execute again from the top. If the user inputs n
than the program should close. I've tried researching this, but only found ways to have the entire console exit and re-open which is not what I want.
Upvotes: 0
Views: 3949
Reputation: 351
My response may be a little late in the game, but thought I'd share a compact version implementing a try-catch method.
Sub Main()
Do
Try
Console.Write("Enter a value: ")
Console.ReadLine()
'...
SomeProcedure()
Catch ex As Exception
Console.WriteLine(ex.ToString)
Finally
Console.Write("Enter another value? (N for No) ")
End Try
Loop Until Console.ReadLine() = "N"
End Sub
Sub SomeProcedure()
'...
End Sub
Upvotes: 0
Reputation: 25810
To detect what the user has entered you have a couple options:
Console.ReadKey()
will read the next keystroke. You can then use a simple Select Case
branch to choose what to do.
You can also use:
Console.ReadLine()
which will return a string (after the user presses enter). You can then use a simple If statement to determine what's in the string (and repeat the query if something other than "y" or "n" was entered.)
Example:
Shared Sub Main()
While True
AverageNums()
Console.WriteLine( "Do you want to run again? (Y/N)" )
Dim key = Console.ReadKey()
If key.Key = ConsoleKey.N Then
Exit While
End If
End While
End Sub
Shared Sub AverageNums()
' ...
End Sub
Upvotes: 2