我需要检查输入是否为空/空。
If input <= 100 And input > 0 And Not input = "" Then
subjectsInt.Add(subjects(i), input)
check = True
End If
我知道在该代码中我将其检查为字符串,但我已经Not input = Nothing
和Not input = 0
并且我收到错误:
运行时异常(第-1行):从字符串“”到“Integer”类型的转换无效。
堆栈追踪:
[System.FormatException:输入字符串的格式不正确。]
[System.InvalidCastException:从字符串“”到“Integer”类型的转换无效。]
有什么建议吗?
修改
以下是您要查看的代码:https://dotnetfiddle.net/0QvoAo
答案 0 :(得分:3)
好吧,我查看了你的代码并且存在许多问题,这些问题都是由于当Option Strict设置为Off时VB.NET允许的数据类型的自由处理引起的。在这种情况下,VB.NET允许您将Console.ReadLine的返回值分配给整数,试图帮助您添加输入的隐式转换。当然,如果用户键入ABCD,则此隐式转换没有其他方式通知您,而不是触发异常。所以我真的,真的建议你使用Option Strict设置为On(MSDN Option Strict)
现在使用Option Strict在你的代码上有很多错误,我已经重写了你的代码,然后在评论中解释了这些变化。
Option Strict On
Imports System
Imports System.Collections.Generic
Public Module Module1
Public Sub Main()
Console.WriteLine("Hello World")
' I use a List of strings instead of an untyped array list
Dim subjects As New List(Of String)() From
{
"Math",
"English",
"German"
}
Dim subjectsInt As New System.Collections.Generic.Dictionary(Of String, Integer)
Dim i, input As Integer
Dim check As Boolean
For i = 0 To subjects.Count - 1
check = False
Do
Console.WriteLine(subjects(i) & ": ")
' The input is passed to a string
Dim temp = Console.ReadLine()
' Check if this string is really a number
If Int32.TryParse(temp, input) Then
If input <= 100 And input > 0 Then
subjectsInt.Add(subjects(i), input)
check = True
End If
End If
Loop While check = False
Next
For i = 0 To subjects.Count - 1
Console.WriteLine(subjects(i) & ": " & subjectsInt(subjects(i)))
Next
Console.ReadLine()
End Sub
End Module
答案 1 :(得分:1)
该错误告诉您input
是一个整数,您无法将整数与字符串进行比较,而这恰好是正在发生的事情。
即使字符串仅包含数字,类型系统也不会将其转换为从运算符推断。
在您的示例中,input = ""
输入永远不会是“”。您应该将输入类型更改为字符串,然后在将其转换为整数之前进行检查。
这将是一个解决方案:
Dim integerInput As Integer
Dim stringInput = Console.ReadLine()
If Integer.TryParse(stringInput, integerInput) AndAlso integerInput <= 100 And integerInput > 0 Then
使用&lt; &GT; = ,需要转换字符串的整数:
If Integer.Parse(input) <= 100 And Integer.Parse(input) > 0 And Not input = "" Then
Integer.Parse 将完成这项工作。
显然,如果你的输入是一个字符串并且不能保证它只包含数字,你需要先做一些检查或使用 Integer.TryParse 。
您可以使用值类型最接近空检查的是EqualityComparer(Of Integer).Default.Equals(id, Nothing)
;除非你开始使用 Nullable ,否则当输入非数字字符串时代码在input = Console.ReadLine()
上失败时为时已晚。