c# - 在不退出循环 C# 的情况下验证来自控制台的输入值
问题描述
假设对于控制台应用程序,我希望用户输入他想扔多少个骰子。Onlu 值 1-5 将被接受。我试过这样做:
Console.WriteLine("How many dices would you like to throw?");
int amount = Convert.ToInt32(Console.ReadLine());
while(true)
{
if(amount < 1 || amount > 5)
{
Console.WriteLine("Please enter a value between 1-5");
break;
}
}
这里的问题是,如果用户输入了一个无效的数字,程序就会停止。我希望它继续询问,直到输入正确的值。有任何想法吗?
干杯。
解决方案
我还没有测试它,但稍微重构了你的代码如下,它应该做你想要的:
Console.WriteLine("How many dices would you like to throw?");
int amount = Convert.ToInt32(Console.ReadLine());
while(amount < 1 || amount > 5)
{
Console.WriteLine("Please enter a value between 1-5");
amount = Convert.ToInt32(Console.ReadLine());
}
编辑:如果你想安全地检查它是否是一个整数值,你可以使用以下版本的代码:
Console.WriteLine("How many dices would you like to throw?");
var input = Console.ReadLine();
while(!int.TryParse(input, out int amount) || amount < 1 || amount > 5)
{
Console.WriteLine("Please enter a value between 1-5");
input = Console.ReadLine();
}
推荐阅读
- java - 在我的活动中执行定期工作请求时,工作管理器向 Worker 类发送错误的输入数据。如何解决?
- python - 多文件错误处理的最佳实践是什么?
- javascript - 我正在尝试获取嵌入的内容
- reactjs - 反应功能组件调用子组件方法
- swiftui - 如何在 SwiftUI 中创建一个获取 View 并返回自定义结果的函数?
- .htaccess - 当 public_html 上存在文件时,apache $1 失败
- ios - 使用代码交换检索令牌时,iOS 上的 Flutter Auth 挂起
- html - 为什么 devtool 中的搜索结果数量急剧下降?
- keyboard - 什么是'¬'字符,它是做什么用的
- html - 使用带有 flex-wrap: wrap 的 Flexbox 时如何使文本换行?