.NET主菜单帮助

时间:2011-07-05 15:49:39

标签: vb.net

我正在尝试创建一个接受用户输入的主菜单,然后检查输入的密码是否有效,以防止我硬编码到数组中的密码。 首先,在for循环中,仅检查第一个密码索引。我想根据ValidPasswords()数组中的EACH密码检查输入的密码。

其次,我的for循环没有做我想做的事。我想给用户3个输入密码的机会...如果他/她超过3,它告诉他们他们已经尝试了3次并退出了表格。现在,它只循环3次并退出而不给用户提供再次尝试的机会。如果我输入一个return语句,它只会继续返回并且不会循环3次。

Public Class frmMain
    Dim ValidPasswords() = {"1234", "2222", "8918", "9911"}
    'Dim ValidPWList As New List(Of String)
    Dim pwIndex As Integer = 0
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    ' For pwIndex = 0 To ValidPasswords.Length 'TOTAL PASSWORDS
    If txtPW.Text = ValidPasswords(pwIndex) Then


    Else
        For i = 0 To 2 '3 MAX ALLOWABLE ATTEMPT
            MessageBox.Show("Invalid Password, Please try again.", "Invalid Credentials")
            txtPW.Focus()
        Next
        MessageBox.Show("Exceeded 3 password attempts.")
        Me.Close()
    End If


    If txtFNAME.Text = "" Then
        MessageBox.Show("Please enter your name!", "Error")
        'ElseIf txtPW.Text <> "1234" And txtPW.Text <> "2332" And txtPW.Text <> "0192" And txtPW.Text <> "2010" Then
        'MessageBox.Show("Invalid Password, Please try again.", "Invalid Credentials")
    Else
        g_welcomeMessage = ("Welcome, " + txtFNAME.Text + " " + txtLNAME.Text + ", to Image Viewer 1.0")
        frmImage.ShowDialog()
    End If


End Sub


Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    MessageBox.Show("Thanks for trying me out!", "Goodbye")
    Me.Close()
End Sub

谢谢!

1 个答案:

答案 0 :(得分:2)

你有事情回到那里丹尼尔。我不会在你的应用程序中提供关于硬编码密码的建议,并假设你只是想要掌握基础知识......我也会假设.Net 4因为你没有指定; - )

我正在手动执行此操作,因此可以解释任何轻微的语法问题:

Public Class frmMain    
    Private validPasswords As List(Of String) = New List(Of String) From {"1234", "2222", "8918", "9911"}    
    Private failedAttempts As Integer = 0    

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click    
    If String.IsNullOrWhitespace(txtFNAME.Text) Then 
        MsgBox("Please enter a name") 
        Return
    End If

    If ValidPasswords.Any(Function(x) String.Equals(txtPW.Text, x)) Then
        ' User has a name and entered a valid password...
        g_welcomeMessage = ("Welcome, " + txtFNAME.Text + " " + txtLNAME.Text + ", to Image Viewer 1.0")
        frmImage.ShowDialog()
    Else
        failedAttempts += 1
        If failedAttempts = 3 Then
            MessageBox.Show("Exceeded 3 password attempts.")
            Me.Close()
        End If
    End If
End Sub

' The other method here...

结束班