Matt Matt - 28 days ago 5
Vb.net 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
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.

JDB JDB
Answer

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