【发布时间】:2019-10-09 19:20:19
【问题描述】:
我在使用 TryParse 捕获用户在哪里输入字符串而不是 int 时无法让我的代码正常工作。如果我按照现在的样子使用它,如果输入了 int 以外的内容,我只会得到 0 的基值。我希望它向用户显示一条错误消息。
尝试过使用 TryParse 的多种不同方式,但都没有真正有用。
static void Main(string[] args)
{
Random r = new Random();
int speltal = r.Next(1,21);
bool play = false;
int myNum;
while (!play)
{
Console.Write("\n\tGuess a number between 1 and 20: ");
Int32.TryParse(Console.ReadLine(), out myNum);
if (myNum < guessNum)
{
Console.WriteLine("\tThe number you have guessed is to low");
Console.ReadLine();
}
if (myNum > guessNum)
{
Console.WriteLine("\tThe number you have guessed is to high");
Console.ReadLine();
}
if (myNum == guessNum)
{
Console.WriteLine("\tCongratulations you guessed the right number!");
Console.ReadLine();
}
我希望它在用户输入除 int 以外的任何内容时向用户显示错误消息。根据我的老师,它还必须包含 TryParse
【问题讨论】:
-
TryParse() 如果成功则返回 true,如果失败则返回 false。不要忽略返回值,而是执行
if (!Int32.TryParse(Console.ReadLine(), out myNum)) { /* report error */ } else { /* do whatever else */ }之类的操作。 They document these things,你知道的。