如果用户没有将字符串作为输入,我可以制作循环吗?

时间:2016-01-25 23:15:30

标签: c#

例如,如果我要求用户给我他的名字(字符串)并且他写了数字,符号或者如果他按 ENTER 我想要一个循环告诉他写字符串以便继续。我为整数做了一个循环,但我不知道如何制作字符串

Console.Write("Please enter the name of the student: ");
//here I made the input to turn into Capitals
name = Console.ReadLine().ToUpper(); 

Console.Write("Please enter their student number: ");
// here I set a condition order to continue. First the input must be integer and second it must be positive
while (!int.TryParse(Console.ReadLine(), out id)||id<0)
{
    Console.ForegroundColor = ConsoleColor.Red;
    Console.Write("The value must be of integer type, try again: ");
    Console.ResetColor();
}

1 个答案:

答案 0 :(得分:1)

Console.Write("Please enter the name of the student: ");
//here I made the input to turn into Capitals
name = Console.ReadLine().ToUpper(); 
if (Regex.IsMatch(name, @"^[a-zA-Z]+$")) { // If letters only
 // Do something
}else{
 Console.WriteLine("Name must contain letters only");
}

Console.Write("Please enter their student number: ");
// here I set a condition order to continue. First the input must be integer and second it must be positive
while (!int.TryParse(Console.ReadLine(), out id)||id<0)
{
    Console.ForegroundColor = ConsoleColor.Red;
    Console.Write("The value must be of integer type, try again: ");
    Console.ResetColor();
}

这应该只检查字母。