我正在尝试编写一些非常基本的代码,但我也在正则表达式上挑战自己。我已经能够将代码搞乱到一定程度,但我真正遇到的问题是我试图在表达式为 false 时运行 do...while 循环。此时我完全没有收到任何错误,但 do...while 循环继续运行。
我在下面附上了相关代码,希望对您有所帮助。
先感谢您
if (tollResponse == "yes")
{
Console.WriteLine("How much do you pay per trip?");
string tollTax = Console.ReadLine();
Match toll = Regex.Match (tollTax, @"[\d .]+");
if (toll.Success)
{
Math.Round(Convert.ToDecimal(tollTax), 2);
Console.WriteLine("Good lord that's high... well it's your money");
}
else
{
do
{
Console.WriteLine("Please enter a proper number");
tollTax = Console.ReadLine();
}
while (toll.Success == false);
}
}
简单的编码错误...添加到代码中的注释来解释问题
if (tollResponse == "yes")
{
Console.WriteLine("How much do you pay per trip?");
string tollTax = Console.ReadLine();
//toll.Success gets set here.
Match toll = Regex.Match(tollTax, @"[\d .]+");
if (toll.Success)
{
//Not sure why you are doing this since you aren't using it in the given code
Math.Round(Convert.ToDecimal(tollTax), 2);
Console.WriteLine("Good lord that's high... well it's your money");
}
else
{
//This is an infinite loop because toll.Success is never set again.
do
{
Console.WriteLine("Please enter a proper number");
tollTax = Console.ReadLine();
} while (toll.Success == false);
}
}
我认为你想要什么
if (tollResponse == "yes")
{
Console.WriteLine("How much do you pay per trip?");
//Loop over the Console.ReadLine() using the else statement and exit if it is right the first time
do
{
string tollTax = Console.ReadLine();
//toll.Success gets set here.
Match toll = Regex.Match(tollTax, @"^[+-]?[0-9]{1,3}(?:,?[0-9]{3})*(?:\.[0-9]{2})?$");
if (toll.Success)
{
Console.WriteLine("Good lord that's high... well it's your money");
//will exit
}
else
{
Console.WriteLine("Please enter a proper number");
}
} while (toll.Success == false);
}
Note:还删除了 1 行重复代码,更新为使用我推荐的正则表达式并删除Math.Round
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)