c# - 如何停止输入没有值的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
解决方案
您可以使用循环和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);
推荐阅读
- optimization - BuildAction() 与普通方式的构建约束的区别
- stun - 如果coturn的外部IP仅用于aws?
- java - 我的 jar 文件在 Windows 中运行良好,但在 linux 中它抛出“线程“主”java.lang.NoClassDefFoundError:javax/jms/JMSException 中的异常”
- ios - 如何使用 Firebase 获取设备令牌?
- manifest - 不同的 Ionic PWA 主页与网页主页
- python - 如何根据另一个列表计算一个项目在列表中出现的次数
- ruby-on-rails - 通过 API 创建和保存 Google 地图(带有地标)
- junit - NullPointerException 测试模拟
- angular - 将 Angular-Material 5 与 Angular 6 一起使用
- elasticsearch - 查询字符串和类型嵌套(elasticsearch)