【问题标题】:Difficulty declaring that user input is not an integer C# [closed]难以声明用户输入不是整数 C# [关闭]
【发布时间】:2012-09-19 20:22:55
【问题描述】:

我可以在这里使用 try catch 场景,但我习惯于说 if x = 30 或 if x > 100,但我需要说的是 if x != int,但我不允许使用它陈述。

我需要的是一种说法,如果用户输入的不等于整数,那么...

      Console.Write("Enter number of cats:"); //cats are 121.45

     var temp = Console.ReadLine();
     int cats;
     if (int.TryParse(temp, out cats))
   {

      price = (cats* 121.45);
   }
  else
 {
    Console.Write{"Number of cats must be an integer. Please enter an integer")
 }


      Console.Write ("Enter number of dogs"); //dogs are 113.35
      int product2 = int.Parse(Console.ReadLine());
      price2 = (dogs * 113.35);
      Console.Write ("Enter number of mice:"); //mice are 23.45
      int mice = int.Parse(Console.ReadLine());
      price3= (mice * 23.45);
      Console.Write("Enter number of turtles:"); //turtles are 65.00
      int turtles = int.Parse(Console.ReadLine());
      price4 = (turtles * 65.00);
      Console.Write("Total price : $");
      grosssales = price1 + price2 + price3 + price4; //PRICE ONE IS NOT RECOGNIZED?
      Console.WriteLine(grosssales);
      Console.ReadKey();
    }

【问题讨论】:

  • 删除整个问题并将其替换为nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn 有什么意义?

标签: c# variables integer declare


【解决方案1】:
var temp = Console.ReadLine();
int cats;
if (int.TryParse(temp, out cats))
{
    // Yay, got the int.
}
else
{
    // Boooo, error.  Do something here to handle it.
}

.TryParse 是你的朋友。

【讨论】:

    【解决方案2】:

    您可以使用int.TryParse 来确定是否可以将用户输入解析为 int。

      var userInput = Console.ReadLine();     
      int cats;
      if(!int.TryParse(userInput, out cats))
      {
          //userInput could not be parsed as an int
      }
      else
      {
          //cats is good
      }
    

    【讨论】:

    • 我不是 if(!... Cleaner 来反转 if 语句的超级粉丝。
    • @JohanLarsson 我通常最终会以这种方式减少嵌套(即坏情况很可能会返回或继续循环)然后没有else。当然,Dyjkstra 不会赞成,因为使用这种风格会导致多个退出点。不过我真的不在乎!
    • 这是我想做的,但是在替换代码之前,可变价格在代码的后面部分变得无法识别。
    • 我的代码中没有price,所以我们只能猜测你的实现。为什么不用更多代码更新您的问题?
    • @user1513637 如果您将 price 声明为 int ,那么以后没有理由不识别它。那个阶段的变量还在范围内吗?
    【解决方案3】:

    使用TryParse:

    int cats;
    if (Int32.Parse(Console.ReadLine(), out cats)) {
      price = cats * 239.99;
      // go on here
    } else {
      Console.WriteLine("The number of cats must be an integer.");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多