【问题标题】:I changed the "Int.TryParse" to while and now my code is not working [closed]我将“Int.TryParse”更改为 while,现在我的代码无法正常工作 [关闭]
【发布时间】:2012-08-21 05:12:29
【问题描述】:
//the code  
parseAttempt = while (KeyBoardInput, out Response);

【问题讨论】:

  • “不工作”是什么意思?
  • //它说不能将类型字符串隐式转换为 bool KeyBoardInput = Console.ReadLine(); parseAttempt = int.TryParse(KeyBoardInput, out Response);
  • 你能发布这个函数的完整代码吗?

标签: c# console while-loop


【解决方案1】:

您不能替换 int.TryParse 与while 循环,但您可以将它 一起使用while 循环,如下所示:

string keyboardInput = Console.ReadLine();

int response;
while (!int.TryParse(keyboardInput, out response)) {
    Console.WriteLine("Invalid input, try again.");
    keyboardInput = Console.ReadLine();
}

另一种方法是将代码重构为单独的方法:

int readIntFromConsole()
{
    while (true)
    {
        string keyboardInput = Console.ReadLine();

        int result;
        if (int.TryParse(keyboardInput, out result))
        {
            return result;
        }
        else
        {
            Console.WriteLine("Invalid input, try again.");
        }
    }
}

【讨论】:

  • 第一次传递时不会取消分配键盘输入吗?
猜你喜欢
  • 2016-11-02
  • 2015-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多