Vb.net 从输入框计算,带有字母输入的错误消息

Vb.net 从输入框计算,带有字母输入的错误消息,vb.net,calculator,inputbox,msgbox,Vb.net,Calculator,Inputbox,Msgbox,我一直被visual basic中一个令人尴尬和恼火的小问题困扰着(正如您可能看到的,我是一个初学者)。问题在于输入字母而不是数字时的错误消息系统。我得到“无法从整数转换为字符串” 在此方面的任何帮助都将不胜感激 这是我的密码: Dim number1, number2 As Integer Dim sum As String number1 = InputBox("first value:") number2 = InputBox("second value:

我一直被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

提前,谢谢:)!

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

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

您的
类型转换错误。改进的代码:

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
的字符串,因此在输入非数值时会引发错误。避免问题的最佳方法是始终依赖正确的类型,如上面的代码所示:输入是字符串,但
是数值
精确地将字符串作为输入。确认正确的输入后,将转换为相应的类型(
Integer
,但您可能需要依赖
Decimal
Double
来计算小数位置)最后,我正在执行到
字符串的转换(只是为了保持此答案的一致性),但请记住VB.NET执行此转换(从数字到字符串)没有任何问题。

啊!现在我明白了,我不认为它可以顺利完成。非常感谢,它成功了:)祝你有一个美好的一天!@user1981481没有问题。你也有同样的问题。仍然给了我同样的问题,因为我的值被错误地设置为整数,我需要一些时间才能处理这个问题:p谢谢祝你今天愉快:)