2013-11-27 52 views
-5

製作一個程序,告訴您密碼是否符合要求。 要求;密碼要求C#WPF

它需要是7個字母或更多。 第一個字母必須是B. 密碼必須至少有3個數字。 密碼必須至少有1個字母。

問:我該如何解決這個問題?一直使用谷歌沒有運氣。我不知道如何設定要求。

Lykilord是指密碼。 這是我迄今所做的:

private void btathuga_Click(object sender, RoutedEventArgs e) 
    { 
     int lykilord = 0; 
     if (lykilord > 7) 
     { 
      MessageBox.Show("Wrong!"); 
     } 
     else if (true) 
     { 
      MessageBox.Show("Wrong!"); 
     } 
+0

什麼是工作?什麼不起作用?你有什麼具體的問題?例如,你需要幫助檢查數字還是字母?計算各種輸入類別?說實話,這看起來像一個家庭作業,你的問題聽起來有點像「請爲我做我的作業」。 – chwarr

+2

我希望這是作業。這些規則非常愚蠢。 – CodesInChaos

+1

您的問題既不明確,也不是您的代碼。 – manish

回答

2

設密碼是你從用戶作爲其密碼得到的字符串。那麼你會接受它,如果

if(password.Length>=7 && 
    password[0]=='B' && 
    password.Where(x => Char.IsDigit(x)).Count()>=3 && 
    password.Where(x => Char.IsLetter(x)).Count()>1) 
{ 
    // The password is ok. Here goes your code. 
} 
0

你有一些要求 - 我將它們分開。

  • 7個字母或更多

您可以通過使用

lykilord.Length(); 
  • 第一個字母必須是B

    lykilord.Substring(0,1); 
    
  • 密碼必須至少有3回本號碼

這裏有幾個選擇。如果您正在使用C#我會使用LINQ,你可以做

int countOfNumbers = lykilord.Count(Char.IsDigit); 
  • 密碼必須至少有1個字母

顯然,如果在開始的B,則是一個字母,如果沒有,那麼它是無效的。但是,如果你想反正檢查字母(備查)

int countOfLetters = lykilord.Count(Char.IsLetter); 

使用所有的這些結合在一起,你可以編譯的,如果這樣的語句:

if (lykilord.Substring(0,1).ToUpper() == "B" && // the ToUpper() will mean they can have either lowercase or uppercase B 
     lykilord.Length() > 7 && 
     countOfNumbers > 3 &&) 
     // i've excluded the letter count as you require the B 
    { 
     // password is good 
    } 
    else 
    { 
     // password is bad 
    } 

我已經做了我最好的分裂它可以讓你從中學習 - 它看起來有點像作業或學術任務的一部分。我們不在這裏爲你做這個作業。

1

這是我從你的問題推斷,可能是這將有助於

private void button1_Click(object sender, EventArgs e) 
{ 
    if (textBox1.Text.Length < 7) 
     { 
      MessageBox.Show("Password can't be less than 7 letter long !"); 
      return; 
     } 
     else if (!textBox1.Text.ToString().Substring(0, 1).Equals("B")) 
     { 
      MessageBox.Show("Password's first letter must be 'B'"); 
      return; 
     } 
     int countOfDigit = 0, countOfLetters = 0; 
     foreach (var digit in textBox1.Text) 
     { 
      if (char.IsDigit(digit)) 
       ++countOfDigit; 
      if (char.IsLetter(digit)) 
       ++countOfLetters; 
     } 
     if (countOfDigit < 3) 
     { 
      MessageBox.Show("Password must have atleast 3 digits"); 
      return; 
     } 

     if (countOfLetters < 1) 
     { 
      MessageBox.Show("Password must have atleast 1 Letter"); 
      return; 
     } 
     MessageBox.Show("Congratulations ! Your Password is as per Norms !"); 
    } 
+0

'goto'!使用'return;'代替。 (相關[SO問題](http://stackoverflow.com/questions/46586/goto-still-considered-有害)和[XKCD](http://xkcd.com/292/))。 – Nasreddine

+0

先生,@Nasreddine我很欣賞你的評論,但如果我使用返回,我不能方便地向用戶顯示恭喜消息。這就是爲什麼。否則,我將不得不使用冗餘代碼。 – manish

+0

是的,沒有任何「冗餘代碼」是可能的。只需將'goto END;'的每個實例替換爲'return;'並刪除標籤'END:;'。 – Nasreddine