【问题标题】:How I get the right exception for wrong Datatype input?我如何获得错误数据类型输入的正确异常?
【发布时间】:2019-08-25 22:58:07
【问题描述】:

抱歉,首先,我是 C# 新手 我正在尝试以正确的方式处理错误的输入! 在我的小型计算器中,我有用于输入和计算的整数,但是当我有如下输入时我该如何处理它:“嗨”,什么不是整数? 如果您再次输入错误并且我不知道如何循环它,我想循环它....

没有类似的东西:if (x != int32) 吗?
我试过这样:

               Console.WriteLine("Enter the first number: ");
               while (!Int32.TryParse(Console.ReadLine(), out x))
               {
                   Console.WriteLine("Invalid input! Try again");
                   if (Int32.TryParse(Console.ReadLine(), out x))
                   {
                       break;
                   }
                }

【问题讨论】:

  • 去掉 if 和 break。它是多余的,如果你逐步了解它,你就会明白它是如何工作的
  • @TheGeneral 非常感谢!!但是有没有像if (x != int32)
  • @Dominik43566 !Int32.TryParse 这正是它的作用

标签: c# exception while-loop int tryparse


【解决方案1】:

您只需要以下内容

int x;

Console.WriteLine("Enter the first number: ");
while (!Int32.TryParse(Console.ReadLine(), out x))
   Console.WriteLine("Invalid input! Try again");

Console.WriteLine($"You had one job and it was a success : {x}");

这是交易

Console.ReadLine() 返回一个字符串,Int32.TryParse( 返回 truefalse 如果它可以将 string 解析为 int

Console.ReadLine()无法解析为int时,循环将不断循环

尽快,不满足循环条件,继续执行到最后一个Console.WriteLine

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    相关资源
    最近更新 更多