程序没有提供所需的解决方案

时间:2016-01-22 19:18:18

标签: vb.net

目标是仅在VB中编写一个代码,用于检查用户ID并查看其格式是否正确。第一个字母应该是大写,接下来的3个应该是小写,接下来的三个应该是数字。我的程序输出"格式不正确"无论。即使我键入正确的格式:

Sub Main()

    Dim userID As String
    Dim a, b, c, d, e, f, g As Integer

    Console.WriteLine("Input User ID")
    userID = Console.ReadLine

    'Take Hall123 as a example of a correct format

    a = Asc(Left(userID, 1))
    'First capital letter

    b = Asc(Mid(userID, 2, 1))
    'First lower case

    c = Asc(Mid(userID, 3, 1))
    'Second lower case

    d = Asc(Mid(userID, 4, 1))
    'Third lower case

    e = Asc(Mid(userID, 5, 1))
    'd contains the first number

    f = Asc(Mid(userID, 6, 1))
    'e contains the second number

    g = Asc(Mid(userID, 7, 1))
    'f contains the third number

    'just checking
    Console.WriteLine(a)
    Console.WriteLine(b)
    Console.WriteLine(c)
    Console.WriteLine(d)
    Console.WriteLine(e)
    Console.WriteLine(f)

    If Len(userID) = 7 Then
        If a >= 65 And a <= 90 Then
            If b >= 97 And b <= 122 And c >= 97 And c <= 122 And d >= 97 And d <= 122 Then
                If e <= 57 And 48 >= e And f <= 57 And 48 >= f And g <= 57 And g >= 48 Then
                    Console.WriteLine("Format is correct")
                Else
                    Console.WriteLine("Format is not correct")
                End If
            Else
                Console.WriteLine("Format is not correct")
            End If

        Else
            Console.WriteLine("Format is not correct")

        End If
    Else
        Console.WriteLine("Format is not correct")
    End If

    Console.ReadKey()

End Sub

我是否正确使用Mid功能?我昨天才研究过它....

1 个答案:

答案 0 :(得分:0)

Mid是.Net前几天的延续,这些天最好使用SubString。您不需要使用任何一种方法来访问字符串中的单个字符。字符串可以被视为Char数组,因此您可以访问(例如)第三个字符userID(2)

确实没有必要将字符转换为ASCII等价物,然后检查这些数字。框架提供了检查字符的方法,以查看它们是字母,数字,大写还是小写等。

您可以使用以下函数检查有效的用户ID

Function CheckUserId(userID As String) As Boolean
    If userID.Length <> 7 Then Return False
    If Not Char.IsUpper(userID(0)) Then Return False

    For i As Integer = 1 To 3
        If Not Char.IsLower(userID(i)) Then Return False
    Next

    For i As Integer = 4 To 6
        If Not Char.IsDigit(userID(i)) Then Return False
    Next
    Return True
End Function

你可以这样的功能:

Sub Main()
    Console.WriteLine("Input User ID")
    Dim userID as String = Console.ReadLine

    If CheckUserId(userID) Then 
        Console.WriteLine("Format is correct")
    Else
        Console.WriteLine("Format is not correct")
    End If
End Sub