首页 > 解决方案 > 如何停止输入没有值的readline

问题描述

希望快速,我只想知道如何停止 Console.Readline(); 在没有实际值的情况下输入。

有问题的代码行:

int xCoordinate = Convert.ToInt32(Console.ReadLine());

有没有一种方法可以阻止用户在不输入值的情况下按下回车键?

当我按下回车键时,我得到以下信息:

未处理的异常。System.FormatException:输入字符串的格式不正确。在 System.Number.ThrowOverflowOrFormatException(ParsingStatus 状态,TypeCode 类型)在 System.Number.ParseInt32(ReadOnlySpan`1 值,NumberStyles 样式,NumberFormatInfo 信息)在 System.Convert.ToInt32(字符串值)在 Battleships_Game.Program.Main(字符串 [ ] args)在 /Users/oliver/Projects/Battleships_Game_Testing/Battleships_Game/Program.cs:line 462

标签: c#

解决方案


您可以使用循环和Int32.TryParse方法:

int xCoordinate = 0;
int failAttemptsCounter = 0;
// this means: WHILE the Conversion result is FALSE go inside the brackets and repeat the step
while (Int32.TryParse(Console.ReadLine(), out xCoordinate) == false)
{
    failAttemptsCounter++;
    Console.WriteLine("Invalid Input, please only integers");
    if (failAttemptsCounter > 10)
    {
        Console.WriteLine("Stop kidding around google what an integer is !");
    }
}

// you end up here only when the conversion has worked
Console.WriteLine(xCoordinate);

推荐阅读