我正在编写一个程序,让用户输入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
答案 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
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
您可以使用简单的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)