C# 允许用户再次输入,直到正确为止
本文关键字:输入 许用户 用户 | 更新日期: 2023-09-27 18:30:27
我正在用c#制作ATM。它的功能之一是让用户在他们的账户之间转账。我怎样才能做到,如果用户输入无效的转账金额(例如负金额),系统将提示用户再次输入金额,直到该金额有效?我尝试使用 while 循环,但一旦我输入负值行"请输入要转账的有效金额",就会不停地重复。
Console.WriteLine("How much would you like to transfer?");
double transferamt = double.Parse(Console.ReadLine());
if (transferamt < 0)
{
Console.WriteLine("Please enter a valid amount to transfer");
}
使用 double.TryParse
.这可确保在用户输入无效格式时不会引发任何引用。根据解析的成功将其包装在一个循环中。
bool valid = false;
double amount;
while (!valid)
{
Console.WriteLine("How much would you like to transfer?");
valid = double.TryParse(Console.ReadLine(), out amount);
}
您需要为负值添加其他验证:
bool valid = false;
double amount;
while (!valid)
{
Console.WriteLine("How much would you like to transfer?");
valid = double.TryParse(Console.ReadLine(), out amount)
&& amount > 0;
}
C# 仅处理确定输出所需的表达式部分。所以在上面的例子中,如果double.TryParse(...)
返回 false,amount > 0
将不会被计算,因为false && anything == false
.
如果值不是有效的双精度值,double.Parse
将引发异常。如果 double.TryParse
在 .NET 版本中不可用,您可以像这样编写自己的版本:
public bool TryParse(string value, out double output)
{
output = 0;
try
{
double = double.Parse(value);
}
catch (Exception ex)
{
return false;
}
}
如果您希望以下尝试使用不同的消息,可以将其稍微重写为:
double amount;
Console.WriteLine("How much would you like to transfer?");
bool valid = double.TryParse(Console.ReadLine(), out amount)
&& amount > 0;
while (!valid)
{
Console.WriteLine("Please enter a valid amount to transfer?");
valid = double.TryParse(Console.ReadLine(), out amount)
&& amount > 0;
}
这可以重构为:
void Main()
{
double amount = GetAmount();
}
double GetAmount()
{
double amount = 0;
bool valid = TryGetAmount("How much would you like to transfer?", out amount);
while (!valid)
{
valid = TryGetAmount("Please enter a valid amount to transfer?", out amount);
}
return amount;
}
bool TryGetAmount(string message, out double amount)
{
Console.WriteLine(message);
return double.TryParse(Console.ReadLine(), out amount)
&& amount > 0;
}
您需要使用 while 循环,但会提示再次阅读。
while(transferamt < 0){
Console.WriteLine("Please enter a valid amount to transfer");
transferamt = double.Parse(Console.ReadLine());
}
您正在使用if
这是一次性条件,如果您想继续重复它直到条件正确,那么您需要使用循环,例如 while
:
double transferamt = -1;
while (transferamt < 0)
{
Console.WriteLine("Please enter a valid amount to transfer");
transferamt = double.Parse(Console.ReadLine());
}
double transferamt=0;
do{
Console.WriteLine("Please enter a valid amount to transfer");
transferamt=double.Parse(Console.ReadLine());
}while(transferamt<0)