首页 > 解决方案 > 如何查看用户是否没有在 C# 中输入有效条目

问题描述

我想知道如果用户在下面的代码中输入了无效条目,如何输出。例如,如果他们输入了字符串字符或字符串字符和数字的组合。现在,如果输入了无效条目,它只会破坏程序。请保留最基本方法的答案,因为我对编程还很陌生!

 Console.Write("Please enter the persons age: ");
 int age = int.Parse(Console.ReadLine());
 if(age == 17)
 {
     Console.WriteLine("That's to bad! You will have to wait until next year!");
 }    
 else if (age < 18)
 {
     Console.WriteLine("That's to bad! You will have to wait a couple years until you can come in!");
 }
 else
 {
     Console.WriteLine("You are of age to be here.");
 }

 while (true)
 {
     Console.Write("Please enter the next persons age: ");
     age = int.Parse(Console.ReadLine());

     if (age == 17)
     {
         Console.WriteLine("That's to bad! You will have to wait until next year!");
     }
     else if (age < 18)
     {
         Console.WriteLine("That's to bad! You will have to wait a couple years until you can come in!");
     }
     else if (age > 18)
     {
          Console.WriteLine("You are of age to be here.");
     }
     else
     {
          Console.WriteLine("Please enter a valid entry");
     }
 }

标签: c#loops

解决方案


你可以做:

int age;

if (int.TryParse(Console.ReadLine(), out age))
{
    if (age > 17)
    {
        Console.WriteLine("That's too bad! You will have to wait until next year!");
    }
    // etc
}
else
{
    Console.WriteLine("Please enter a valid input");
}

说明

int.TryParse是一个接受 anstring并尝试将其转换为 an 的方法int,如果转换成功,它将结果分配给age变量并返回 true 导致程序进入if块,否则返回false并且程序进入else块。该age变量是通过使用 C# 的输出参数功能分配的,这是一种将变量从外部传递给方法的方法,而后者承诺它将为其分配一些值。


推荐阅读