[英]VB.Net Converting from string to double
我的程序中有一個嚴重的錯誤,如果用戶在文本框中沒有輸入時按下檢查(計算)按鈕,程序將顯示此錯誤:“從字符串“”轉換為“ Double”類型無效。” 我想解決此問題,但不確定如何進行轉換。 我原本以為是CType,但我聽到有人在解析。 我該怎么辦? 文本框稱為mskTxtInput,按鈕對象稱為btnCheck,它執行所有計算和處理。
更新:這是我的代碼,除了解析方法外,希望對您有所幫助!
私有Sub btnCheck_Click(ByVal發送者作為System.Object,ByVal e作為System.EventArgs)處理btnCheck.Click pic1.Visible = False'隱藏圖片pic1.Image = My.Resources.A pic2.Image = My.Resources.F
Dim value As Double
If Double.TryParse(mskTxtInput.Text, value) = Then
MsgBox("parsing success") ' parsing worked, so use the value in here
Else
MsgBox("parsing failed") ' parsing failed, so alert the user to that fact
End If
If radAdd.Checked = True Then
totalNum = num1 + num2
End If
If radSub.Checked = True Then
totalNum = num1 - num2
End If
If radMulti.Checked = True Then
totalNum = num1 * num2
End If
If mskTxtInput.Text = totalNum Then
lblAns.Text = ("Correct!")
lblAns2.Text = ("Answer is " & totalNum)
pic1.Visible = True
wins = wins + 1
nScore = wins
Else
lblAns.Text = ("Incorrect")
lblAns2.Text = ("Answer should be " & totalNum)
pic2.Visible = True
End If
attempts = attempts + 1
If attempts = 5 Then
MessageBox.Show("Game Finished! ", "End Of Game", _
MessageBoxButtons.OK, _
MessageBoxIcon.Exclamation)
lblAns.Text = ("You scored " & wins & " Out of 5")
btnSpin.Enabled = False
pic1.Visible = False
pic2.Visible = False
lblAns2.Text = ""
lblAns2.Text = "Play again?"
btnCheck.Enabled = False
btnNew.Enabled = True
attempts = 0
wins = 0
End If
mskTxtInput.Clear()
mskTxtInput.Focus()
End Sub
嘗試使用Double.TryParse方法(字符串,雙精度)代替
就像是
Dim s As String
Dim result As Double
Dim returnValue As Boolean
returnValue = Double.TryParse(s, result)
使用TryParse
方法進行解析,以避免解析失敗時出現異常:
Dim value As Double
If Double.TryParse(mskTxtInput.Text, value) Then
' parsing worked, so use the value in here
Else
' parsing failed, so alert the user to that fact
End If
將iVar變暗為整數dim sStr作為字符串
sstr =“”
ivar = val(sstr)
使用靜態方法Double.TryParse()
。 如果返回true,則解析成功,您可以繼續進行該操作。 如果返回false,則說明解析不成功,您應該顯示一條錯誤消息(如果需要,請使用MessageBox
)並中止操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.