VB控制台应用程序输入验证实现求助
Hey there! I see you're just getting started with VB and stuck on adding input validation to your console menu—no worries, this is a super common hurdle, and we can fix it easily.
Here's your updated code with proper input validation that ensures users enter a valid number between 1 and 5:
Dim choiceNum As String Dim validChoice As Integer Dim isValid As Boolean = False Console.WriteLine("1] Accuracy Option") Console.WriteLine("2] Quadratic Equation") Console.WriteLine("3] Monte-Carlo Integration") Console.WriteLine("4] Prime Decision") Console.WriteLine("5] Exit") Console.WriteLine() ' Loop until we get a valid input Do While Not isValid Console.Write("Please enter the number that corresponds to your choice: ") choiceNum = Console.ReadLine() ' Try to convert the input to an integer without crashing the app If Integer.TryParse(choiceNum, validChoice) Then ' Check if the integer falls within our menu's valid range If validChoice >= 1 AndAlso validChoice <= 5 Then isValid = True Else Console.WriteLine("Oops! Please enter a number between 1 and 5.") End If Else Console.WriteLine("Hmm, that's not a valid number. Letters, symbols, or empty input won't work—give it another go!") End If Loop ' Now you can use the validated choice in your program logic Console.WriteLine($"You selected option {validChoice}")
Let's break down what's working here:
- Do-Loop: This keeps prompting the user for input until they enter something valid—no skipping past the menu with bad inputs.
- Integer.TryParse: This is way safer than using
CInt()directly. It checks if the input string can be converted to an integer, and returnsTrueonly if it works. No crashes if someone types "abc" or a random symbol! - Range Check: Once we confirm it's a number, we make sure it matches one of your menu options (1-5). If not, we give a clear, friendly error message to guide the user.
This setup handles all edge cases: non-numeric inputs, numbers outside your menu range, even blank entries!
内容的提问来源于stack exchange,提问作者Noctis Ren
相关产品推荐
相关产品推荐

