C# 在不退出循环C的情况下验证控制台的输入值#
比如说,对于一个控制台应用程序,我希望用户输入他想要掷多少骰子。仅接受1-5的U值。我试着这样做:C# 在不退出循环C的情况下验证控制台的输入值#,c#,validation,console,C#,Validation,Console,比如说,对于一个控制台应用程序,我希望用户输入他想要掷多少骰子。仅接受1-5的U值。我试着这样做: 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 ent
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(“您想掷多少骰子?”);
int amount=Convert.ToInt32(Console.ReadLine());
while(true)
{
如果(金额<1 | |金额>5)
{
Console.WriteLine(“请输入介于1-5之间的值”);
打破
}
}
这里的问题是,如果用户输入了无效的数字,程序就会停止。我希望它继续询问,直到输入正确的值。有什么想法吗
干杯。我还没有测试它,但对您的代码进行了如下轻微的重构,它应该可以满足您的需要:
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(“您想掷多少骰子?”);
int amount=Convert.ToInt32(Console.ReadLine());
而(金额<1 | |金额>5)
{
Console.WriteLine(“请输入介于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();
}
Console.WriteLine(“您想掷多少骰子?”);
var input=Console.ReadLine();
而(!int.TryParse(输入,输出整数金额)| |金额<1 | |金额>5)
{
Console.WriteLine(“请输入介于1-5之间的值”);
input=Console.ReadLine();
}
您可能需要检查输入的值是否为整数
int amount;
Console.WriteLine("How many dices would you like to throw?");
do
{
if (int.TryParse(Console.ReadLine(), out var i))
{
if (i >= 1 && i <= 5)
{
amount = i;
break;
}
Console.WriteLine("The integer value is not between 1 and 5");
}
{
Console.WriteLine("The value you entered is not an integer");
}
} while (true);
int金额;
控制台。WriteLine(“你想掷多少骰子?”);
做
{
if(int.TryParse(Console.ReadLine(),out变量i))
{
如果(i>=1&&i=1&&i)这里的问题是,每次用户输入无效的int,输入值的问题就应该输出。这个解决方案只允许用户输入任何其他数字…不管它值多少…单词“dice”在英语中是复数(单数是“die”-真的)。
int amount;
Console.WriteLine("How many dices would you like to throw? Or enter 'X' to exit.");
do
{
var input = Console.ReadLine();
if(input.Equals("X", StringComparison.InvariantCultureIgnoreCase))
{
return;
}
if (int.TryParse(input, out var i))
{
if (i >= 1 && i <= 5)
{
amount = i;
break;
}
Console.WriteLine("The integer value is not between 1 and 5");
}
{
Console.WriteLine("The value you entered is not an integer");
}
} while (true);