2010-11-18 95 views
1

我在我的節目一個糟糕的錯誤:如果一個用戶按下檢查(計算)按鈕時出現在文本框中的程序顯示此錯誤代碼輸入:「從字符串轉換‘’鍵入'Double'是無效的。「我想解決這個問題,但我不確定如何進行轉換。我在想可能是CType,但我正在聽說解析。我如何去做這件事?該文本框稱爲mskTxtInput,該按鈕對象稱爲btnCheck,它執行所有計算和處理。VB.Net從字符串轉換爲加倍

更新:這是我的代碼,除了解析方法,所以希望這有助於一點!

私人小組btnCheck_Click(BYVAL發件人爲System.Object的,BYVALË作爲System.EventArgs)把手btnCheck.Click pic1.Visible =假「隱藏圖片 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 
+0

請分享一些代碼中發生此問題。 – BeemerGuy 2010-11-18 08:30:49

+0

這與您的問題沒有直接關係,但看起來您並未使用Option Strict。我建議你打開它:然後編譯器會生成有關危險代碼的警告,從長遠來看可以節省您的時間。 – MarkJ 2010-11-18 11:17:49

回答

2

使用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 
+0

嘿!我使用你的代碼,但提出了「解析通過」和「解析失敗」的消息框修改,並不斷收到「解析失敗」,我可以顯示代碼,並希望它有一點幫助! – 2010-11-18 08:59:21

+0

@William Mc:您在發佈的代碼中的'Then'之前放置了一個'='運算符,因此它不會運行。刪除它,它的作品。我已驗證,如果解析成功,代碼將顯示第一個消息框。 – Guffa 2010-11-18 13:13:55

+0

我拿走了=運算符,但它仍然沒有工作:(VS處處彰顯這一行黃:如果mskTxtInput.Text = totalNum然後 – 2010-11-18 20:46:53

0

暗淡的Ivar作爲整數 暗淡SSTR作爲字符串

SSTR = 「」

的ivar = VAL(SSTR)

0

使用靜態方法Double.TryParse()。如果它返回true,則解析成功,您可以繼續操作。如果返回false,則解析不成功,並且應顯示錯誤消息(如果需要,則使用MessageBox)並中止操作。