public static void addpatron()
{
Console.WriteLine("You have selected to add a Patron.");
string first, last, city, state = "", street, email, temp;
int zip = 0;
long number = 0;
Console.WriteLine("Please Provide a First Name: ");
first = Console.ReadLine();
Console.WriteLine("Please Provide a Last Name: ");
last = Console.ReadLine();
Console.WriteLine("Please Provide a Street Address: ");
street = Console.ReadLine();
Console.WriteLine("Please Provide a City Name: ");
city = Console.ReadLine();
Console.WriteLine("Please Provide a Email Id: ");
email = Console.ReadLine();
int f = 0;
while (f == 0)
{
Console.WriteLine("Please Provide a State Name: ");
state = Console.ReadLine();
if (state.Length == 2)
{
Regex r = new Regex(@"([A-Za-z][A-Za-z])");
Match m = r.Match(state);
if (m.Success)
f = 1;
}
}
while (f == 1)
{
Console.WriteLine("Please Provide a Zip Code: ");
temp = Console.ReadLine();
if (temp.Length == 5)
{
Regex r = new Regex(@"([0-9]{5})");
Match m = r.Match(temp);
if (m.Success)
{
zip = int.Parse(temp);
if (zip / 10000 != 0)
f = 0;
}
}
}
while (f == 0)
{
Console.WriteLine("Please Provide a Mobile Number: ");
temp = Console.ReadLine();
if (temp.Length == 10)
{
Regex r = new Regex(@"([0-9]{10})");
Match m = r.Match(temp);
if (m.Success)
{
number = long.Parse(temp);
if (number / 100000000 != 0)
f = 1;
}
}
}
MainClass.patron.Add(MainClass.user, new Info { firstname = first, lastname = last, street = street, state = state, city = city, zip = zip, phone = number, email = email });
displayUser.display(MainClass.user);
MainClass.user++;
MainClass.Menu();
}
答案 0 :(得分:0)
缩短代码有一些可能性:
您可以使用do {} while (condition);
循环。这样,您可以决定是否在输入后离开循环。
您不需要变量,决定是否停止循环。您可以在循环条件中检查所有条件(在您的情况下非常容易)。
您可以使用^
=字符串的开头和$
=字符串锚点的结尾和{5}
作为匹配的长度来检查带有正则表达式的字符串的长度。
您还可以简化正则表达式以忽略大小写。
您的分组操作似乎只是检查,输入的第一个数字与0
不同。您也可以使用正则表达式进行检查。
您可以使用静态Regex.IsMatch()
方法,该方法返回true
或false
。
例如检查状态
do {
Console.WriteLine("Please Provide a State Name: ");
state = Console.ReadLine();
} while (!RegEx.IsMatch(state, @"^[a-z]{2}$", RegexOptions.IgnoreCase))
检查邮政编码。只有int.TryParse()
返回Regex.Match()
并且是一种方便的方法,才会执行true
来解析和分配表达式中的值。
do {
Console.WriteLine("Please Provide a ZIP Code: ");
tmp = Console.ReadLine();
} while (!(RegEx.IsMatch(tmp, @"^[1-9][0-9]{4}$") && int.TryParse(tmp, out zip)));