面试题答案
一键面试- 将字符串类型的数字转换为整型数据:
- 在Visual Basic中,可以使用
CInt
函数将字符串类型的数字转换为整型数据。例如:
Dim strNumber As String Dim intNumber As Integer strNumber = "123" intNumber = CInt(strNumber)
- 在Visual Basic中,可以使用
- 字符串中包含非数字字符的情况:
- 如果字符串中包含非数字字符,使用
CInt
函数会引发InvalidCastException
异常。例如:
Dim strNumber As String Dim intNumber As Integer strNumber = "12a" intNumber = CInt(strNumber) '这行代码会引发异常
- 如果字符串中包含非数字字符,使用
- 处理这种情况的方法:
- 方法一:使用
IsNumeric
函数判断: 可以先使用IsNumeric
函数判断字符串是否完全由数字组成,只有判断为True
时才进行转换。Dim strNumber As String Dim intNumber As Integer strNumber = "12a" If IsNumeric(strNumber) Then intNumber = CInt(strNumber) Else '处理非数字字符串的逻辑,比如提示错误 MsgBox "字符串包含非数字字符,无法转换。" End If
- 方法二:使用异常处理:
使用
On Error Resume Next
语句或者Try...Catch
结构(在支持结构化异常处理的版本中)来捕获并处理异常。- 使用
On Error Resume Next
:
Dim strNumber As String Dim intNumber As Integer strNumber = "12a" On Error Resume Next intNumber = CInt(strNumber) If Err.Number <> 0 Then '处理异常,比如提示错误 MsgBox "字符串包含非数字字符,无法转换。" Err.Clear End If On Error GoTo 0
- 使用
Try...Catch
(.NET环境下):
Dim strNumber As String Dim intNumber As Integer strNumber = "12a" Try intNumber = CInt(strNumber) Catch ex As Exception '处理异常,比如提示错误 MsgBox "字符串包含非数字字符,无法转换。" End Try
- 使用
- 方法一:使用