我的代码有问题。这是我们不久前在学校的活动,我无法完成它。问题是如果我在第一次尝试时在任何帐户中输入正确的用户名和密码,即使它显示“欢迎(用户名)”,然后输入“输入用户名>>”,“无效输入”仍会显示我必须再次输入用户名和密码,直到我完成3次尝试然后代码结束(与第二次尝试相同,在第三次尝试中“无效输入”仍然显示)。我该怎么办?我将在代码中添加或删除哪些内容?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
String username;
String password;
String[,] accnts = { {"cads123","dadada"},{"carladrian","fafafa"},{"delossantos","gagaga"}};
int row;
for (int x = 3; x >= 1; x-- )
{
Console.WriteLine("You have "+ x + " attempt/s.");
Console.Write("Enter Username>> ");
username = Console.ReadLine();
Console.Write("Enter Password>> ");
password = Console.ReadLine();
for (row = 0; row < 3; row++)
{
if (username.Equals(accnts[row,0]) && password.Equals(accnts[row,1]))
{
Console.WriteLine("Welcome "+accnts[row,0]+"!");
break;
}
else
{
Console.WriteLine("Invalid Input.");
if (x != 1)
{
Console.WriteLine("Please Try Again.");
Console.Write("\n");
}
else if (x.Equals(1))
{
Console.Write("Goodbye!");
break;
}
}
}
}
Console.ReadKey();
}
}
}
答案 0 :(得分:1)
using System;
namespace ConsoleApplication1
{
internal class Program
{
private static void Main(string[] args)
{
String username;
String password;
String[,] accnts = { { "cads123", "dadada" }, { "carladrian", "fafafa" }, { "delossantos", "gagaga" } };
int row;
bool isValideUser = false;
for (int x = 3; x >= 1; x--)
{
Console.WriteLine("You have " + x + " attempt/s.");
Console.Write("Enter Username>> ");
username = Console.ReadLine();
Console.Write("Enter Password>> ");
password = Console.ReadLine();
for (row = 0; row < 3; row++)
{
if (username.Equals(accnts[row, 0]) && password.Equals(accnts[row, 1]))
{
Console.WriteLine("Welcome " + accnts[row, 0] + "!");
isValideUser = true;
break;
}
}
if (!isValideUser)
{
Console.WriteLine("Invalid Input.");
if (x != 1)
{
Console.WriteLine("Please Try Again.");
Console.Write("\n");
}
else if (x.Equals(1))
{
Console.Write("Goodbye!");
break;
}
}
else
{
break;
}
}
Console.ReadKey();
}
}
}
答案 1 :(得分:0)
不是在String [,]中存储用户名和密码,而是可以将Dictionary与Key,Value对一起使用。密钥是用户名,值是密码。我可以在这里编写代码,因为你说的是你的任务。也许你可以尝试一下。请尝试以下代码。
String username;
String password;
String[,] accnts = { { "cads123", "dadada" }, { "carladrian", "fafafa" }, { "delossantos", "gagaga" } };
int row = 0, x = 3;
bool loggedIn = false;
do
{
Console.WriteLine("You have " + x + " attempt/s.");
Console.Write("Enter Username>> ");
username = Console.ReadLine();
Console.Write("Enter Password>> ");
password = Console.ReadLine();
for (row = 0; row < 3; row++)
{
if (username.Equals(accnts[row, 0]) && password.Equals(accnts[row, 1]))
{
Console.WriteLine("Welcome " + accnts[row, 0] + "!");
loggedIn = true;
break;
}
}
if (loggedIn)
{
break;
}
else
{
Console.WriteLine("Invalid Input.");
if (x != 1)
{
Console.WriteLine("Please Try Again.");
Console.Write("\n");
}
else if (x.Equals(1))
{
Console.Write("Goodbye!");
break;
}
}
} while (--x > 0);