The example in this article describes how the Go language calculates the number of days in a specified month. Share to everyone for your reference. The implementation methods are as follows:
Copy Code code as follows:
Package Main
Import (
"FMT"
"Bufio"
"OS"
"RegExp"
"StrConv"
)
Func Main () {
Year: = Input ("year", "^[0-9]{1}[0-9]{3}$")
Month: = Input ("month", "^ (0{1}[0-9]{1}|1{1}[0-2]{1}) $")
Count (year, month)
Fmt. Println ("Press Enter button to continue ...")
Reader: = Bufio. Newreader (OS. Stdin)
Lastinput, _, Err: = Reader. Readrune ()
If Err!= nil {
Fmt. Fprintln (OS. Stderr, "occur error when input (last) '", Lastinput, "':", err)
}
Return
}
Func count (year int, month int) (days int) {
If month!= 2 {
If month = = 4 | | Month = 6 | | Month = 9 | | Month = 11 {
Days = 30
} else {
days = 31
Fmt. Fprintln (OS. Stdout, "The Month has");
}
} else {
If ((year% 4) = = 0 && (year% 100)!= 0) | | (year% 400) = = 0) {
days = 29
} else {
Days = 28
}
}
Fmt. fprintf (OS. Stdout, "The%d-%d has%d days.\n", year, month, days)
Return
}
Func input (name string, regexptext string) (number int) {
var validnumber = False
For!validnumber {
Fmt. PRINTLN ("Please input a", Name, ":")
Reader: = Bufio. Newreader (OS. Stdin)
Inputbytes, _, Err: = Reader. ReadLine ()
If Err!= nil {
Fmt. Fprintln (OS. Stderr, "occur error when input", name, ":", Err)
Continue
}
Inputtext: = String (inputbytes)
ValidNumber, err = RegExp. Matchstring (Regexptext, Inputtext)
If Err!= nil {
Fmt. Fprintln (OS. Stderr, "occur error when match", Name, "(", Inputtext, "):", err)
Continue
}
If ValidNumber {
Number, err = StrConv. Atoi (Inputtext)
If Err!= nil {
Fmt. Fprintln (OS. Stderr, "occur error when convert", Name, "(", Inputtext, "):", err)
Continue
}
} else {
Fmt. Fprintln (OS. Stdout, "The", Name, "(", Inputtext, ") does not have the correct format!")
}
}
Fmt. PRINTLN ("The input", name, ":", Number)
Return
}
I hope this article will help you with your go language program.