我现在已经乱了一个多小时了。即使阅读Stackoverflow解决方案,我仍然不知道如何解决它。该程序使用第一个用户名和密码(测试和密码),当我输入第二个用户名和密码(aaa& 123)时,它不起作用。
public partial class Form2 : Form
{
String[] username = { "test", "aaa" };
String[] password = { "password", "123" };
private void btnSubmit_Click(object sender, EventArgs e)
{
try
{
for (int i = 0; i < username.Length; i++) // <------- Unreachable Code
{
if ((txtUsername.Text.Trim() == username[i]) && (txtPassword.Text.Trim() == password[i]))
{
MessageBox.Show("Login Successful. Welcome!", "Login Success", MessageBoxButtons.OK, MessageBoxIcon.None);
Form3 frm3 = new Form3();
frm3.Visible = true;
frm3.Activate();
break;
}
else
{
MessageBox.Show("You have entered an invalid input. Do you want to try again?", "Invalid Input", MessageBoxButtons.YesNo, MessageBoxIcon.Hand); break;
}
}
}
catch(Exception x)
{
MessageBox.Show("System Error! Please try again!", "System Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
}
}
}
答案 0 :(得分:4)
break
个分支中都有if-else
个字词。从else中删除break
。但是你会在每个循环上得到消息框。因此,您需要修改代码:在循环外移动消息框。
答案 1 :(得分:0)
您的代码中存在逻辑流控制问题。因此,您需要在循环外部移动MessageBox。
如果修改代码以使用列表而不是数组并包含一些LINQ,则可以完全脱离循环,并且可以从较少的嵌套中受益。
public partial class Form2 : Form
{
List<string> username = new List<string>{ "test", "aaa" };
List<string> password = new List<string>{ "password", "123" };
private void btnSubmit_Click(object sender, EventArgs e)
{
try
{
if (txtUsername.Text.Length > 0 && txtPassword.Text.Length > 0
&& username.Any(x => x == txtUsername.Text.Trim())
&& password.Any(x => x == txtPassword.Text.Trim()))
{
MessageBox.Show(
"Login Successful. Welcome!",
"Login Success", MessageBoxButtons.OK, MessageBoxIcon.None);
Form3 frm3 = new Form3();
frm3.Visible = true;
frm3.Activate();
}
else
{
MessageBox.Show(
"You have entered an invalid input. Do you want to try again?",
"Invalid Input",
MessageBoxButtons.YesNo, MessageBoxIcon.Hand);
}
}
catch(Exception x)
{
MessageBox.Show(
"System Error! Please try again!", "System Error",
MessageBoxButtons.OK, MessageBoxIcon.Hand);
}
}
}