This question already has answers here:
How can I validate console input as integers?
(9个答案)
5年前关闭。
我无法弄清楚要放在方括号中的内容以使程序检查输入的内容是否为数字。如果没有,我想返回一个错误,然后重新启动过程。有什么建议么?
前导空格。
尾随空格
作为一个数字麦粒肿。
(9个答案)
5年前关闭。
我无法弄清楚要放在方括号中的内容以使程序检查输入的内容是否为数字。如果没有,我想返回一个错误,然后重新启动过程。有什么建议么?
bool running = true;
Console.Write("Enter the number of victims so we can predict the next murder, Sherlock: ");
while (running)
{
victimCount = int.Parse(Console.ReadLine());
if (/*I want victimCount only to be accepted if it's a number*/)
{
Console.Write("\nThat's an invalid entry. Enter a correct number!: ");
}
else
{
running = false;
}
}
最佳答案
我希望受害者计数仅在为数字时才被接受
您可以改用int.TryParse
方法。它返回boolean
值,表明您的值是否是有效的int
。
string s = Console.ReadLine();
int victimCount;
if(Int32.TryParse(s, out victimCount))
{
// Your value is a valid int.
}
else
{
// Your value is not a valid int.
}
Int32.TryParse
方法默认使用NumberStyles.Integer
。这意味着您的字符串可以具有;CurrentCulture
的前导符号。 (PositiveSign
或NegativeSign
)前导空格。
尾随空格
作为一个数字麦粒肿。
关于c# - C#如果语句readline必须等于数字,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24889685/