While 循环以确认用户输入 [英] While loop to confirm user input

查看:49
本文介绍了While 循环以确认用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个无法结束 while 循环的 c# 问题.

I am stuck on a c# issue where I cant get the while loop to end.

userValue 是程序中较早输入的字符串.

userValue is a string that is input earlier on in the program.

字符串采用DateTime格式,新输入需要匹配原来的userValue.I.E 确认用户的原始出生日期.

The string is formatted in DateTime, and the new input need to match the original userValue. I.E Confirming the the users original birth date.

我使用 try/catch 来确定输入是否可以解析为 DateTime.

I used a try / catch to determine if the input can be parsed to DateTime.

目前它只是一个恒定循环,一旦用户的出生日期得到验证,我就试图让循环停止.

Currently it is just a constant loop, i'm trying to have the loop stop once the users birth date is verified.

string userValueTwo;

int stop = 0;
while (stop != 0)
{
    Console.WriteLine("Please verify your birth date");
    userValueTwo = Console.ReadLine();

     try
     {
        DateTime birthdayTwo = DateTime.Parse(userValueTwo);
     }
     catch
     {
         Console.WriteLine("You did not enter a valid format.");
         Console.ReadLine();
     }

     if (userValueTwo == userValue)
     {
         Console.WriteLine("Birth date confirmed.");
         Console.ReadLine();
     }

    else 
    {
        Console.WriteLine("Your birthday did not match our records. Please try again");
        Console.ReadLine();
    }
}

推荐答案

您可以在确认日期后使用 break 声明,尽管不推荐使用.

You may use the break statement after the date is confirmed, although it is not reccommended.

既然你已经实现了停止条件,那么只要在日期确定后将stop设置为1,while循环就不会继续运行了.

Since you have already implemented a stop condition, just set stop to 1 after the date is confirmed and the while loop will not continue running.

这是使用布尔值的更好解决方案:

Here's a better solution using a boolean:

bool stop = false;
while (!stop)
{
    Console.WriteLine("Please verify your birth date");
    userValueTwo = Console.ReadLine();

     try
     {
        DateTime birthdayTwo = DateTime.Parse(userValueTwo);
     }
     catch
     {
         Console.WriteLine("You did not enter a valid format.");
         Console.ReadLine();
     }

     if (userValueTwo == userValue)
     {
         Console.WriteLine("Birth date confirmed.");
         Console.ReadLine();
         stop = true;
     }

    else 
    {
        Console.WriteLine("Your birthday did not match our records. Please try again");
        Console.ReadLine();
    }
}

这篇关于While 循环以确认用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆