消息框出现时不应该出现?

时间:2015-04-20 23:44:06

标签: vb.net

我正在创建一个程序,用户输入月份并返回天数。如果用户输入的内容不是一个月,则应该说“"请输入有效的月份"但前提是它不是一个真正的月份。问题是即使输入了有效月份,消息框也会一直显示。

Dim monthname() As String = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}
Dim monthdays() As String = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}

For i = 0 To monthname.GetUpperBound(0)
    If monthname(i) = TextBox1.Text Then
        TextBox2.Text = monthname(i) & " has " & monthdays(i) & " days"
    End If
Next

If String.Compare(TextBox1.Text, monthname(11)) <> 0 Then
    MessageBox.Show("Please enter a vaild month")
End If

3 个答案:

答案 0 :(得分:1)

这是因为您只是将输入的值与monthname(11)进行比较。您需要运行循环并与每个值进行比较。

答案 1 :(得分:1)

如果您想检查文本框是否包含任何有效的月份名称,您只能检查它是否等于上个月。相反,您可以声明一个默认为False的布尔变量(称为found),如果文本框与其中一个月份名称匹配,则将其设置为True。我认为以下代码可以满足您的需求。它对月份名称进行不区分大小写的比较;如果你想拒绝&#34;可能&#34;和&#34; MAY&#34;并且只接受&#34; May&#34 ;,在String.Compare语句中将True更改为False。

Dim monthName() As String = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}
Dim monthDays() As Integer = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
Dim found As Boolean

For i As Integer = 0 To monthName.GetUpperBound(0)
    If String.Compare(monthName(i), TextBox1.Text, True) = 0 Then
        TextBox2.Text = monthName(i) & " has " & monthDays(i).ToString & " days"
        found = True
        Exit For
    End If
Next

If Not found Then MessageBox.Show("Please enter a valid month")

答案 2 :(得分:1)

我建议你稍微改变一下。

不是使用两个必须手动输入代码的数组,而是首先构建一个月数据字典并使用它。

从这开始:

Dim months = _
    Enumerable _
        .Range(0, 12) _
        .Select(Function(n) New DateTime(2015, n + 1, 1).AddMonths(1).AddDays(-1.0)) _
        .ToDictionary( _
            Function(x) x.ToString("MMMM").ToLowerInvariant(), _
            Function(x) x.Day)

这会为您提供一个字典,将月份名称映射到天数。

dictionary

现在您可以编写方法的其余部分,而不仅仅是这样:

Dim entered = TextBox1.Text.Trim().ToLowerInvariant()

If months.ContainsKey(entered) Then
    Dim proper = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(entered)
    TextBox2.Text = String.Format("{0} has {1} days", proper, months(entered))
Else
    MessageBox.Show("Please enter a vaild month")
End If