[英]Validation through Try-Catch block C#
I am a beginner at C# and I am trying to use a 'Try and catch' block to act as a validation when the user inputs something. 我是C#的初学者,当用户输入内容时,我尝试使用“ Try and catch”块作为验证。 It works when the user enters an invalid input the first time but the system crashes when the user enters an invalid input the second time.
当用户第一次输入无效的输入时,它起作用,但是当用户第二次输入无效的输入时,系统崩溃。
I tried to get through this problem by creating a bool variable which is set true until user inputs correct input but have not been very successful. 我试图通过创建一个布尔变量来解决这个问题,该变量设置为true,直到用户输入正确的输入但还不是很成功。
The main problem is I don't know how to make the system set the bool variable to false when the user inputs a correct input 主要问题是当用户输入正确的输入时,我不知道如何使系统将bool变量设置为false
C# Code: C#代码:
while (invalidInput == true)
{
try
{
{
Console.Write("Landscape Size: ");
LandscapeSize = Convert.ToInt32(Console.ReadLine());
Console.Write("Initial number of warrens: ");
InitialWarrenCount = Convert.ToInt32(Console.ReadLine());
Console.Write("Initial number of foxes: ");
InitialFoxCount = Convert.ToInt32(Console.ReadLine());
Console.Write("Randomness variability (percent): ");
Variability = Convert.ToInt32(Console.ReadLine());
FixedInitialLocations = false;
}
Sim = new Simulation(LandscapeSize, InitialWarrenCount, InitialFoxCount, Variability, FixedInitialLocations);
}
catch
{
Console.WriteLine("invalid input!");
LandscapeSize = Convert.ToInt32(Console.ReadLine());
InitialWarrenCount = Convert.ToInt32(Console.ReadLine());
InitialFoxCount = Convert.ToInt32(Console.ReadLine());
Variability = Convert.ToInt32(Console.ReadLine());
invalidInput = true;
}
invalidInput = false;
}
Also, I am new to stack overflow so sorry if I make any mistakes. 另外,我是堆栈溢出的新手,所以如果出现任何错误,我们深表歉意。
So my question is what am I doing wrong? 所以我的问题是我做错了什么? Thank you
谢谢
The problem your having is that invalidInput is set to false every time the loop is executed - independent of the try-catch block. 您遇到的问题是每次执行循环时都将invalidInput设置为false-与try-catch块无关。 Move it to the end of the try-block instead, this way you will ensure that all the code in the try-block does not throw an error before you set the flag.
而是将其移至try块的末尾,这样,您将确保在设置该标志之前try块中的所有代码均不会引发错误。 However, since exceptions rarely are used for control-flow you should probably use some kind of control-statement like an if-statement .
但是,由于异常很少用于控制流,因此您可能应该使用某种控制语句,例如if语句 。
You only need to set invalidInput
to false
at the end of the try block
. 您只需要在
try block
的末尾将invalidInput
设置为false
。
However, use int.TryParse
to control flow instead of exceptions. 但是,请使用
int.TryParse
来控制流而不是异常。
int landscapeSize;
Console.Write("Landscape Size: ");
while(!int.TryParse(Console.ReadLine(), out landscapeSize))
{
Console.Write("Invalid input. Enter landscape size: ");
}
Do this for all your inputs. 为您的所有输入执行此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.