有效的电话号码包含:
少于9个字符,开头是"+",只有数字.
我试图使用正则表达式,但我只是开始使用它们,我不擅长它.我到目前为止的代码是:
static void Main(string[] args)
{
Console.WriteLine("Enter a phone number.");
string telNo = Console.ReadLine();
if (Regex.Match(telNo, @"^(\+[0-9])$").Success)
Console.WriteLine("correctly entered");
else
Console.WriteLine("incorrectly entered");
Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)
但我不知道如何以这种方式检查字符串的长度.任何帮助表示赞赏.
我有这个代码来验证电话号码,但它看起来有点尴尬.我猜这是一个更好的方法来解决这个问题.我怎样才能提高效率呢?
public static bool validTelephoneNo(string telNo)
{
bool condition = false;
while (condition == false)
{
Console.WriteLine("Enter a phone number.");
telNo = Console.ReadLine();
if (telNo.Length > 8)
{
if (telNo.StartsWith("+") == true)
{
char[] arr = telNo.ToCharArray();
for (int a = 1; a < telNo.Length; a++)
{
int temp;
try
{
temp = arr[a];
}
catch
{
break;
}
if (a == telNo.Length - 1)
{
condition = true;
}
}
}
}
}
return true;
}
Run Code Online (Sandbox Code Playgroud) 我正在为学校做一个简单的课程项目,以试验 C# 中的继承和其他要点,但我在某些部分遇到了问题。我相信我需要在无条件 while 循环中尝试捕获,以确保用户以正确的形式输入数据,但我还需要能够从错误处理代码中跳出循环。我在给我带来问题的代码下面添加了注释。
class Program : students
{
static void Main(string[] args)
{
students stu = new students();
Console.Write("Number of students are you recording results for: ");
int studNum = int.Parse(Console.ReadLine());
stu.setNoOfStudents(studNum);
Console.WriteLine();
for (int a = 0; a < studNum; a++)
{
Console.Write("{0}. Forename: ", a + 1);
stu.setForname(Console.ReadLine());
Console.Write("{0}. Surname: ", a + 1);
stu.setSurname(Console.ReadLine());
while (0 == 0)
{
try
{
Console.Write("{0}. Age: ", a + 1);
stu.setstudentAge(int.Parse(Console.ReadLine()));
Console.Write("{0}. Percentage: ", a + 1);
stu.setpercentageMark(int.Parse(Console.ReadLine())); …Run Code Online (Sandbox Code Playgroud)