c# - 如何查看用户是否未在 C# 中输入有效条目

标签 c# loops

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

 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");
     }
 }

最佳答案

你可以这样做:

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 是一种接受string 并尝试将其转换为int 的方法,如果转换成功则分配结果赋给age变量并返回true导致程序进入if block ,否则返回false并且程序进入否则 block 。 age 变量是通过使用 C# 的 output parameters feature 赋值的。这是一种将变量从外部传递给方法的方法,而后者 promise 会为其分配一些值。

关于c# - 如何查看用户是否未在 C# 中输入有效条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52617051/

相关文章:

c# - DataGridView:如何选择整个列并取消选择其他所有内容?

c# - dapper.net 中的多映射

loops - 在循环 Dataframe 中读取 CSV 文件 (Julia)

c++ - 在 Arduino 中制作更好的循环

c# - 我想强制渲染,但尽可能快地绘制 (InvalidateVisual/CompositionTarget.Rendering)

c# - Android应用程序和Winform应用程序之间发送和接收消息

loops - 为什么在循环宏中有一个 = 符号用于从文件中读取行?

c - 即使条件不为真,C 中的 while 循环也会退出

javascript - 如何在按下按键时暂停/播放 Javascript 循环?

C# 异步/等待未观察到的异常