Go语言计算指定年月天数的方法
本文实例讲述了Go语言计算指定年月天数的方法。分享给大家供大家参考。具体实现方法如下:
packagemain import( "fmt" "bufio" "os" "regexp" "strconv" ) funcmain(){ 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("PressEnterbuttontocontinue...") reader:=bufio.NewReader(os.Stdin) lastInput,_,err:=reader.ReadRune() iferr!=nil{ fmt.Fprintln(os.Stderr,"Occurerrorwheninput(last)'",lastInput,"':",err) } return } funccount(yearint,monthint)(daysint){ ifmonth!=2{ ifmonth==4||month==6||month==9||month==11{ days=30 }else{ days=31 fmt.Fprintln(os.Stdout,"Themonthhas31days"); } }else{ if(((year%4)==0&&(year%100)!=0)||(year%400)==0){ days=29 }else{ days=28 } } fmt.Fprintf(os.Stdout,"The%d-%dhas%ddays.\n",year,month,days) return } funcinput(namestring,regexpTextstring)(numberint){ varvalidNumber=false for!validNumber{ fmt.Println("Pleaseinputa",name,":") reader:=bufio.NewReader(os.Stdin) inputBytes,_,err:=reader.ReadLine() iferr!=nil{ fmt.Fprintln(os.Stderr,"Occurerrorwheninput",name,":",err) continue } inputText:=string(inputBytes) validNumber,err=regexp.MatchString(regexpText,inputText) iferr!=nil{ fmt.Fprintln(os.Stderr,"Occurerrorwhenmatch",name,"(",inputText,"):",err) continue } ifvalidNumber{ number,err=strconv.Atoi(inputText) iferr!=nil{ fmt.Fprintln(os.Stderr,"Occurerrorwhenconvert",name,"(",inputText,"):",err) continue } }else{ fmt.Fprintln(os.Stdout,"The",name,"(",inputText,")doesnothavethecorrectformat!") } } fmt.Println("Theinput",name,":",number) return }
希望本文所述对大家的Go语言程序设计有所帮助。