【问题标题】:Calculating from inputboxes, with error message for letter input从输入框计算,带有字母输入的错误消息
【发布时间】:2013-09-15 09:17:49
【问题描述】:

我一直在努力解决 Visual Basic 中一个令人尴尬和烦人的小问题(正如您可能看到的,我是初学者)。问题是输入字母而不是数字时的错误消息系统。我得到“无法从整数转换为字符串。

对此的任何帮助将不胜感激。

这是我的代码:

    Dim number1, number2 As Integer
    Dim sum As String

    number1 = InputBox("first value:")
    number2 = InputBox("second value:")
    sum = number1 + number2

    If IsNumeric(sum) Then
        MsgBox("The sum of the numbers " & number1 & " and " & number2 & " is: " & sum)
    ElseIf Not IsNumeric(sum) Then
        MsgBox("You may only type numbers into the fields!, trie again")
    End If

提前谢谢你:)!

【问题讨论】:

    标签: vb.net calculator inputbox msgbox


    【解决方案1】:

    您错误地进行了Type 转换。改进的代码:

    Dim input1, input2 As String
    
    input1 = InputBox("first value:")
    input2 = InputBox("second value:")
    
    If IsNumeric(input1) And IsNumeric(input2) Then
        MsgBox("The sum of the numbers " & input1 & " and " & input2 & " is: " & (Convert.ToInt32(input1) + Convert.ToInt32(input2)).ToString())
    Else
        MsgBox("You may only type numbers into the fields!, try again")
    End If
    

    InputBox 通过将它们与整数类型变量相关联来返回隐式转换为Integer 的字符串,因此在输入非数字值时会引发错误。避免问题的最佳方法是始终依赖正确的类型,如上面的代码所示:输入是字符串,但IsNumeric 将精确的字符串作为输入。一旦确认了正确的输入,就会执行到相应类型的转换(Integer,但您可能希望依靠DecimalDouble 来计算小数位)并使用数字类型执行mathematica 运算。最后,我正在执行到String 的转换(只是为了保持这个答案的一致性),但请记住,VB.NET 会隐式执行此转换(从数字到字符串),没有任何问题。

    【讨论】:

    • 啊!现在明白了,没想到能这么顺利。非常感谢,它成功了 :) 祝你有美好的一天!
    • @user1981481 没问题。你也一样。
    【解决方案2】:

    在您的数字框上进行验证,以便它们必须是数字,而不仅仅是您的总和。

    If Not IsNumeric(number1) Then
      MsgBox("You may only type numbers into the fields!, try again")
    End If
    
    If Not IsNumeric(number2) Then
      MsgBox("You may only type numbers into the fields!, try again")
    End If
    

    【讨论】:

    • 仍然给我同样的问题,因为我的值被错误地设置为整数,我需要一些时间才能掌握这个:P 谢谢你,祝你有美好的一天:)跨度>
    猜你喜欢
    • 2012-06-03
    • 2016-04-15
    • 2013-10-28
    • 2021-12-09
    • 2018-07-15
    • 1970-01-01
    • 1970-01-01
    • 2012-02-06
    • 1970-01-01
    相关资源
    最近更新 更多