我的学校代码有一个基本问题。代码需要作为控制台程序询问用户输入,但在继续操作之前,我需要它在输入空字段时重复这个问题。到目前为止,我已经尝试了很多while循环!isStringNullorEmpty,stringlength,试图创建一个函数来检查它和一些if语句。这两件事我都做不了。程序一直进行到最后。
System.Console.Write("Give first name");
String firstname = System.Console.ReadLine();
System.Console.Write("Give last name");
String lastname = System.Console.ReadLine();
System.Console.Write("Give date of birth");
DateTime = dt = DateTime.Parse(System.Console.ReadLine();
您可以尝试
string firstName = null;
Console.WriteLine("Give first name");
while(string.IsNullOrWhiteSpace(firstName = Console.ReadLine()))
Console.WriteLine("OMG you had one job as a user of this application, to put in the right value!");
您可以对DateTime
执行相同操作
Console.Write("Give date of birth");
while (!DateTime.TryParse(Console.ReadLine(),out var dob))
Console.Write("OMG you had one job as a user of this application, to put in the right value!");
其他资源
DateTime.TryParse方法
将指定的日期和时间的字符串表示形式转换为其DateTime等效,并返回一个值,该值指示转换成功。
您可以编写
System.Console.Write("Give first name");
String firstname = null;
while(firstname==null || firstname==""){
firstname = System.Console.ReadLine();
}
试试这个:
String lastname = null;
Console.Write("Give last name: ");
while (!String.IsNullOrEmpty(lastname)) {
lastname = System.Console.ReadLine();
}
试试这个
var firstname = string.Empty;
var lastname = string.Empty;
var dt = DateTime.MinValue;
do
{
System.Console.Write("Give first name");
firstname = System.Console.ReadLine();
} while (string.IsNullOrEmpty(firstname));
do
{
System.Console.Write("Give last name");
lastname = System.Console.ReadLine();
} while (string.IsNullOrEmpty(lastname));
do
{
System.Console.Write("Give date of birth");
dt = DateTime.Parse(System.Console.ReadLine());
} while (dt != DateTime.MinValue);
尝试这个
bool value = true;
while (value==true)
{
System.Console.Write("Give first name");
String firstname = System.Console.ReadLine();
if (firstname == "")
{
value = false;
break;
}
System.Console.Write("Give last name");
String lastname = System.Console.ReadLine();
if (lastname == "")
{
value = false;
break;
}
System.Console.Write("Give date of birth");
DateTime dt = DateTime.Parse(System.Console.ReadLine());
if (dt.ToString()=="")
{
value = false;
break;
}
}