Matt Matt - 9 months ago 53 Question

VB.NET Have whole program loop until user decides to exit?

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
than I want the program to execute again from the top. If the user inputs
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.

Answer Source

To detect what the user has entered you have a couple options:


will read the next keystroke. You can then use a simple Select Case branch to choose what to do.

You can also use:


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.)


Shared Sub Main()    
    While True
        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