Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何停止在没有值的情况下输入readline_C# - Fatal编程技术网

C# 如何停止在没有值的情况下输入readline

C# 如何停止在没有值的情况下输入readline,c#,C#,希望是一个快速的例子,我只想知道如何停止控制台;在没有实际值的情况下输入 有关代码行: int xCoordinate = Convert.ToInt32(Console.ReadLine()); 有没有一种方法可以阻止用户在不输入值的情况下按enter键 当我按enter键时,我得到以下信息: 未处理的异常。System.FormatException:输入字符串的格式不正确。 at System.Number.ThrowOverflowOrFormatException(ParsingSt

希望是一个快速的例子,我只想知道如何停止控制台;在没有实际值的情况下输入

有关代码行:

int xCoordinate = Convert.ToInt32(Console.ReadLine());
有没有一种方法可以阻止用户在不输入值的情况下按enter键

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

未处理的异常。System.FormatException:输入字符串的格式不正确。 at System.Number.ThrowOverflowOrFormatException(ParsingStatus状态,类型代码类型) 位于System.Number.ParseInt32(只读span`1值、NumberStyles样式、NumberFormatInfo信息) 在System.Convert.ToInt32处(字符串值) 在/Users/oliver/Projects/Battleships\u Game\u Testing/Battleships\u Game/Program.cs中的Battleships\u Game.Program.Main(字符串[]args)中


试着把它放在一个循环中。将用户的输入输入到变量中,并检查空值。您可以使用do-while循环来执行此操作。如果检测到null异常,还可以提示用户输入有效的整数

tryParse(string, Int32)

这是最好的选择。您可以用谷歌搜索它,帮助避免使用循环。

您可以使用循环和方法:


处理此场景的典型方法是使用验证循环。为了简单起见,我建议将逻辑提取到单独的方法中。下面是一个简单的例子:

int ReadInteger(string prompt)
{
    while (true)
    {
        Console.WriteLine(prompt);
        var response = Console.ReadLine();
        int result;
        if (int.TryParse(response, out result)) return result;
    }
}

你可以试试那样的

int xCoordinate =0;
    while(true){
        try{
        xCoordinate = Convert.ToInt32(Console.ReadLine());
            break;
        }
        catch{

        }
    }
Console.WriteLine(xCoordinate);

是否要异步等待输入?将用户输入读入变量。然后检查它是否有效。如果不是,请不要尝试将其转换为整数。无论如何,您都需要处理无效输入,如字母和标点符号。正如knight8989所回答的那样,在得到一个有效的输入之前,最好继续接受输入。
int xCoordinate =0;
    while(true){
        try{
        xCoordinate = Convert.ToInt32(Console.ReadLine());
            break;
        }
        catch{

        }
    }
Console.WriteLine(xCoordinate);