C# 没有输入值时程序崩溃
我创建了一个程序,遇到了一个问题。当我调试程序时,没有输入一个值,例如一个数字,然后按几次enter按钮,程序最终崩溃。我想知道是否有一个验证规则可以放在适当的地方,这样程序就不会在没有输入值时崩溃C# 没有输入值时程序崩溃,c#,C#,我创建了一个程序,遇到了一个问题。当我调试程序时,没有输入一个值,例如一个数字,然后按几次enter按钮,程序最终崩溃。我想知道是否有一个验证规则可以放在适当的地方,这样程序就不会在没有输入值时崩溃 int userChoice; static void Main(string[] args) { new Program().Welcome(); } public void Welcome() { Console.WriteLine("
int userChoice;
static void Main(string[] args)
{
new Program().Welcome();
}
public void Welcome()
{
Console.WriteLine(" HELLO");
Console.ReadLine();
Main_Menu();
}
private void Main_Menu()
{
Console.WriteLine("1). Welcome");
Console.WriteLine("2). Help Facilities");
Console.WriteLine("3). Exit");
userChoice = Convert.ToInt16(Console.ReadLine());
Options();
}
private void Options()
{
if (userChoice == 1)
{
Console.Clear();
Console.WriteLine("Welcome.....................");
Console.ReadLine();
}
if (userChoice == 2)
{
Console.Clear();
Console.WriteLine("Help.........................");
Console.ReadLine();
}
if (userChoice == 3)
{
//if user selects option 3 the program will exit
}
不要只是解析,使用try parse验证它是否是一个数字 下面是一些整数类型(整数)的简写
- long=Int64
- int=Int32
- short=Int16
- byte=(如果存在,将是Int8)
int t;
if(int.TryParse(Console.ReadKey(),out t){
//Do work with the number t
}
else{
//Handle a non numerical input
}
如果将空字符串放入
Convert.ToInt16
中,它将抛出FormatException
。因此,最好尝试将输入解析为整数,并在出现错误时让用户重新输入
short s;
while (!short.TryParse(Console.ReadLine(), out s))
{
Console.WriteLine("Input invalid. Retry.");
}
(自从您在示例代码中使用short
以来,我一直使用int
)使用此主菜单()
方法代替您的方法。您将获得平滑的输出
private void Main_Menu()
{
Console.WriteLine("1). Welcome");
Console.WriteLine("2). Help Facilities");
Console.WriteLine("3). Exit");
string userChoiceSTR = Console.ReadLine();
if (!string.IsNullOrEmpty(userChoiceSTR))
{
userChoice = Convert.ToInt16(userChoiceSTR);
try
{
Options();
}
catch
{
Console.WriteLine("Did not put any value. Please Select a menu: ");
Main_Menu();
}
}
else {
Console.WriteLine("Did not put any value. Please Select a menu: ");
Main_Menu();
}
}
如果问题是崩溃,请提供崩溃日志您尚未粘贴完整的代码使用
Int.TryParse()
而不是Convert.ToInt()
。这将尝试转换数字并返回一个bool
指示是否成功。您不需要这个new Program().Welcome()代码>只需调用Welcome()代码>在主功能中。我假设Main
所在的父类确实已经是Program
。@JasonEvansMain
是一个静态方法,而Welcome
不是,因此,确实有必要在main中创建一个类实例。非常感谢您,这对我帮助很大。我是一名学生,在大学里学习这门课程。我是否可以为输入的仅介于1到3之间的数字制定另一个验证规则,而不会使程序崩溃或退出。@Naz是的,使用if测试值解析值