我可以在这里使用try catch场景,但我习惯说x = 30或者x> 100,但我需要说的是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();
}
答案 0 :(得分: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
是你的朋友。
答案 1 :(得分: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
}
答案 2 :(得分: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.");
}