0

我可以在这里使用 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();
    }
4

3 回答 3

4
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是你的朋友。

于 2012-09-27T23:53:05.843 回答
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
  }
于 2012-09-27T23:52:52.750 回答
0

使用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.");
}
于 2012-09-27T23:53:57.350 回答