重复问题,如果用户输入在C#中为空

时间:2018-11-13 08:01:39

标签: c# loops

我的学校代码存在基本问题。该代码需要将用户输入作为控制台程序,但是在继续之前,当我输入一个空字段时,我需要它来重复该问题。到目前为止,我已经尝试了很多while循环,!isStringNullorEmpty,string.lengths,试图创建一个检查它和一些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();

5 个答案:

答案 0 :(得分:1)

您可以尝试

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 Method

  

将日期和时间的指定字符串表示形式转换为其   等效于DateTime,并返回一个值,该值指示   转换成功。

答案 1 :(得分:0)

你可以写

   System.Console.Write("Give first name");
   String firstname = null;
   while(firstname==null || firstname==""){
       firstname = System.Console.ReadLine();
   }

答案 2 :(得分:0)

尝试一下:

String lastname = null;

Console.Write("Give last name: ");

while (!String.IsNullOrEmpty(lastname)) {
    lastname = System.Console.ReadLine();
}

答案 3 :(得分:0)

尝试一下

            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);

答案 4 :(得分:0)

尝试

        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;
            }
        }