2015-09-02 63 views
2

我正在研究一個VB程序,而非基本的(沒有雙關語意圖),我需要將基本整數轉換爲羅馬數字。我的轉換部分與我的Select Case完美配合。我還需要添加驗證輸入,因此如果輸入了無效號碼,文本框就會如此顯示。 1到10之間的任何數字都應該能夠點擊轉換按鈕。目前,我在1和10之間輸入的任何號碼都會立即顯示「該號碼無效」。當整數處於有效方式內時輸入無效?

這是我的當前代碼,這將失敗:

Public Class Form1 

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load 

End Sub 

Private Sub lblRomanNum_Click(sender As Object, e As EventArgs) 

End Sub 

Private Sub txtBox1_TextChanged(sender As Object, e As EventArgs) Handles txtBox1.TextChanged 
    Dim intNum As Integer 
    If intNum < 1 Or intNum > 10 Then 
     txtBox1.Text = "That number is invalid." 
     'ElseIf intNum > 10 Then 
     'txtBox1.Text = "That number is invalid" 
    End If 

End Sub 

Private Sub txtBox2_TextChanged(sender As Object, e As EventArgs) Handles txtBox2.TextChanged 

End Sub 

Private Sub btnConvert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConvert.Click 
Select CInt(txtBox1.Text) 
     Case 1      ' numerical 1 
      txtBox2.Text = "I" 
     Case 2      ' numerical 2 
      txtBox2.Text = "II" 
     Case 3      ' numerical 3 
      txtBox2.Text = "III" 
     Case 4      ' numerical 4 
      txtBox2.Text = "IV" 
     Case 5      ' numerical 5 
      txtBox2.Text = "V" 
     Case 6      ' numerical 6 
      txtBox2.Text = "VI" 
     Case 7      ' numerical 7 
      txtBox2.Text = "VII" 
     Case 8      ' numerical 8 
      txtBox2.Text = "VIII" 
     Case 9      ' numerical 9 
      txtBox2.Text = "IX" 
     Case 10      ' numerical 10 
      txtBox2.Text = "X" 
      'Case Else 
      'If a user enters an invalid value, this message is displayed and no conversion is attempted, according to instructions. 
      'txtBox2.Text = "That value is invalid." 
    End Select 

End Sub 

Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click 
    Me.Close() 
End Sub 

Private Sub lblRomanNum_Click_1(sender As Object, e As EventArgs) 

End Sub 
End Class 

不限intNum小於1應顯示無效消息。

任何大於10的intNum都應顯示無效消息。

如果我正在閱讀我目前正確閱讀的內容,則應該可以正常工作,並允許輸入介於1到10之間的數字,而不會顯示無效消息。我在這裏錯過了什麼嗎?

回答

1

嘗試支架和 '或'

1. Dim intNum As Integer 
2. If (intNum < 1) or (intNum > 10) Then 
3.  txtBox1.Text = "That number is invalid." 
4. End If 
+0

無可否認,您的建議仍然會導致無效的消息。 –

+0

然後您需要顯示您在另一個控件中獲得的值;也許這不是你認爲應該的。 –

0

您的代碼完全符合的.NET Framework 4.5.1爲我工作在Visual Studio 2013。嘗試刪除整個區塊並重新輸入代碼。 或者你可以試試這個代碼以及

If intNum < 1 OrElse intNum > 10 Then 
    TextBox1.Text = "That number is invalid." 
End If 
+0

無可避免地,您的建議仍然會導致無效的消息。 –

+0

您已更改問題。 'Dim intNum As Integer'是聲明,'intNum'它總是0.所以代碼按預期工作。 – Dush

0

需要添加...

Integer.TryParse(txtBox1.Text, i) 

...直接下我的變量聲明。