欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Go语言计算指定年月天数的方法

程序员文章站 2022-11-15 22:21:40
本文实例讲述了go语言计算指定年月天数的方法。分享给大家供大家参考。具体实现方法如下: 复制代码 代码如下:package main import (  &...

本文实例讲述了go语言计算指定年月天数的方法。分享给大家供大家参考。具体实现方法如下:

复制代码 代码如下:
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 31 days");
        }
    } 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
}

希望本文所述对大家的go语言程序设计有所帮助。