我想用 "while "功能,让用户每次输入错误的用户名或密码时,CMD都会告诉用户 "用户名错了。"或者 "密码错了"。我现在算是做到了,用户可以多次输入,直到得到正确的答案,问题是CMD并没有告诉用户他们使用的用户名密码是错误的! 我将把整个代码贴在这里。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hello
{
class Program
{
static void Main(string[] args)
{
string name = "Michael";
string pass = "coolguy";
int time = 12;
string NameInput;
string PassInput;
string Exit = "Y";
string ExitInput;
Console.Write("\nPlease, enter the time: ");
time = int.Parse(Console.ReadLine());
if (time <= 12)
{
Console.WriteLine("\nGood Morning. It's " + time + " AM");
}
else if (time > 12)
{
Console.WriteLine("\nGood Evening. It's " + time + " PM");
}
Console.WriteLine("\nPlease, enter your name.");
do NameInput = Console.ReadLine();
while (NameInput != name);
Console.WriteLine("\n Welcome, Michael. Please, enter your password: ");
do PassInput = Console.ReadLine();
while (PassInput != pass);
Console.WriteLine("\nYou successfully have logged in.");
Console.WriteLine("\nType (Y) to log out.");
ExitInput = Console.ReadLine();
if (ExitInput == Exit)
{
return;
}
}
}
}
通过在 "do-while "语句里面嵌套一个 "if "语句来修正。
Console.WriteLine("\n Welcome, Michael. Please, enter your password: ");
do
{
PassInput = Console.ReadLine();
if(PassInput != pass)
{
Console.WriteLine("\nWrong password.");
}
} while (PassInput != pass);