显示1到12之间数字的用户输入的月份名称

时间:2017-03-23 12:13:44

标签: vb.net

我正在编写一个程序,让用户输入1到12之间的数字,并显示该月份的月份名称。

这是我创建的程序,但这不是执行该任务的最简单,最有效的方法。有更简单的方法吗?

Dim Month As Integer
Console.WriteLine("Which month is it?")
Month = Console.ReadLine()

Select Case Month
    Case 1
        Console.WriteLine("January")
    Case 2
        Console.WriteLine("February")
    Case 3
        Console.WriteLine("March")
    Case 4
        Console.WriteLine("April")
    Case 5
        Console.WriteLine("May")
    Case 6
        Console.WriteLine("June")
    Case 7
        Console.WriteLine("July")
    Case 8
        Console.WriteLine("August")
    Case 9
        Console.WriteLine("September")
    Case 10
        Console.WriteLine("October")
    Case 11
        Console.WriteLine("November")
    Case 12
        Console.WriteLine("December")
    Case Else
        Console.WriteLine("Error.")
End Select

3 个答案:

答案 0 :(得分:0)

Dim Month As Integer
Dim name as string
Console.WriteLine("Which month is it?")
Month = Console.ReadLine()
'check if the month is a number
If Not Integer.TryParse(Month) Then
   console.writeline("Error")
End If
' Set Abbreviate to True to return an abbreviated name or false for full name
name = MonthName(Month, True)
console.writeline("you entered : " & Name)
' name now contains "Apr" or if set to false is "April" (on the assumption of input of 4.

答案 1 :(得分:0)

我首先会使用Integer.TryParse来确保输入实际上是Integer

有几种方法可以从Integer等效项中检索月份名称。

使用DateTime

Console.WriteLine("Which month is it?")

Dim monthInput As Integer
If Integer.TryParse(Console.ReadLine(), monthInput) Then

    Try
        Console.WriteLine(New DateTime(1, monthInput, 1).ToString("MMMM"))
    Catch ex As ArgumentOutOfRangeException
        Console.Write(ex.Message)
    End Try

End If

使用DateAndTime.MonthName

Console.WriteLine("Which month is it?")

Dim monthInput As Integer
If Integer.TryParse(Console.ReadLine(), monthInput) Then

    Try
        Console.WriteLine(DateAndTime.MonthName(monthInput))
    Catch ex As ArgumentException
        Console.Write(ex.Message)
    End Try

End If

使用answer已在此MonthName中显示的那个。

您可以使用简单的Try[...]Catch声明替换If代码,以验证monthInput实际上是有效的月份:

Console.WriteLine("Which month is it?")

Dim monthInput As Integer
If Integer.TryParse(Console.ReadLine(), monthInput) Then

    If monthInput >= 1 AndAlso monthInput <= 12 Then
        'Use one of the following methods:

        'Console.WriteLine(New DateTime(1, monthInput, 1).ToString("MMMM"))
        'Console.WriteLine(DateAndTime.MonthName(monthInput))
        'Console.WriteLine(MonthName(monthInput))
    Else
        Console.WriteLine(String.Format("{0} is not a valid month input.", monthInput))
    End If

End If

答案 2 :(得分:0)

取决于您认为容易的事情:

Dim month = CInt(Val(Console.ReadLine))

Console.WriteLine(If(month >= 1 AndAlso month <= 12, MonthName(month), "Error."))

对于文化不变月份,MonthName(month)可以替换为

System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat.GetMonthName(month)