2016-01-22 53 views
0

目的是編寫一個只有VB的代碼,它將檢查用戶ID並查看它是否處於正確的格式。第一個字母應該是大寫字母,下三個字母應該是小寫字母,接下來的三個字母應該是數字。無論如何,我的程序都輸出「格式不正確」。即使我輸入正確的格式:程序沒有給出所需的解決方案

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函數功能?我昨天才研究過它......

+0

您是否檢查了調試窗口以驗證a,b,c,d,e,f和g是他們應該是什麼? – TMH8885

+0

我對正則表達式並不擅長,但對於正則表達式來說,這似乎是一個很好的例子。你有沒有使用正則表達式的原因?找到文檔[here](https://msdn.microsoft.com/en-us/library/hs600312(v = vs.110).aspx) –

回答

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