2015-10-11 99 views
1

我一直在搞亂了一個多小時。即使閱讀Stackoverflow解決方案,我仍然不知道如何解決它。該程序與第一個用戶名和密碼(測試&密碼)一起工作,當我輸入第二個用戶名和密碼(aaa & 123)它不起作用。C#無法檢測到代碼

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

你不需要在'if'聲明打破。 –

+0

請不要執行catch(Exception x)'。這不好。只要讓例外冒出來,否則你就隱藏了錯誤。例如,在這種情況下,可以在這裏處理'Form3'中的任何錯誤。那很糟。那是你要的嗎? – Enigmativity

回答

4

你必須在這兩個if-else分支break字。從其他地方刪除break。但是你會在每個循環中獲得消息框。所以你需要修改你的代碼:在循環之外移動消息框。

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); 
     } 
    } 
} 
相關問題