程序没有给出所需的解决方案
问题描述:
目的是编写一个只有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函数功能?我昨天才研究过它......
答
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
您是否检查了调试窗口以验证a,b,c,d,e,f和g是他们应该是什么? – TMH8885
我对正则表达式并不擅长,但对于正则表达式来说,这似乎是一个很好的例子。你有没有使用正则表达式的原因?找到文档[here](https://msdn.microsoft.com/en-us/library/hs600312(v = vs.110).aspx) –