Q1 从命令行终端中输入一个英文月份,然后输出这个月份在今年有多少天
input: go run days-in-month.go april
output: 30
package main
import (
"fmt"
"os"
"strings"
"time"
)
func main() {
if len(os.Args) != 2 {
fmt.Println("Give me a month name")
return
}
year := time.Now().Year()
leap := year%4 == 0 && (year%100 != 0 || year%400 == 0)
days, month := 28, os.Args[1]
switch strings.ToLower(month) {
case "april", "june", "september", "november":
days = 30
case "january", "march", "may", "july",
"august", "october", "december":
days = 31
case "february":
if leap {
days = 29
}
default:
fmt.Printf("%q is not a month.\n", month)
return
}
fmt.Printf("%q has %d days.\n", month, days)
}
Q2 从终端输入+-*/% 和一个数字,输出该数字的矩阵。
go run dynamic-table.go + 4
package main
import (
"fmt"
"os"
"strconv"
"strings"
)
const (
ValidOps = "%+-*/"
UsageMsg = "Usage:[op="+ValidOps+"] [size]"
sizeMissingMsg = "Size is missing"
InvalidOpMsg =`Invalid operator. Valid ops one of:` + ValidOps
InvalidOp = -1
)
func main(){
args := os.Args
switch len(args[1:]){
case 1:
fmt.Println(sizeMissingMsg)
fallthrough
case 0:
fmt.Println(UsageMsg)
return
}
indexNum := strings.IndexAny(args[1],"+-*/%")
if indexNum < 0 {
fmt.Println(InvalidOpMsg)
return
}
size,err :=strconv.Atoi(args[2])
if err != nil || size < 0 {
fmt.Println(InvalidOpMsg)
return
}
fmt.Printf("%5s",args[1])
for i := 0;i <=size;i++{
fmt.Printf("%5d",i)
}
fmt.Println()
for i := 0; i<=size;i++{
fmt.Printf("%5d",i)
for j :=0;j<=size;j++{
var res int
switch args[1]{
case "+":
res = i+j
case "-":
res = i -j
case "*":
res = i * j
case "/":
if j !=0 {
res=i/j
}
case "%":
if j != 0{
res = i % j
}
}
fmt.Printf("%5d", res)
}
fmt.Println()
}
}
Q3 随机猜数字游戏
package main
import (
"fmt"
"math/rand"
"os"
"strconv"
"time"
)
const (
maxTurns = 5 // less is more difficult
usage = `Welcome to the Lucky Number Game! 🍀
The program will pick %d random numbers.
Your mission is to guess one of those numbers.
The greater your number is, harder it gets.
Wanna play?
`
)
func main() {
rand.Seed(time.Now().UnixNano())
args := os.Args[1:]
if len(args) != 2 {
// fmt.Println("Pick a number.")
fmt.Printf(usage, maxTurns)
return
}
var verbose bool
if args[0]=="-v"{
verbose=true
}
guess, err := strconv.Atoi(args[1])
if err != nil {
fmt.Println("Not a number.")
return
}
if guess < 0 {
fmt.Println("Please pick a positive number.")
return
}
for turn := 0; turn < maxTurns; turn++ {
n := rand.Intn(guess + 1)
if verbose {
fmt.Printf("%d ", n)
}
if n == guess {
switch rand.Intn(3){
case 0:
fmt.Print("🎉 YOU WIN!\n")
case 1:
fmt.Print("🎉 YOU'RE AWESOME! \n")
case 2:
fmt.Print("🎉 PERFECT! \n")
}
return
}
}
fmt.Println("☠️ YOU LOST... Try again?")
}
Q4 使用lable + continue or break 跳出循环的操作
break 用来终止 for , select , switch 语句,且仅能用在有这三个语句的地方
continue 只用在 for 语句中,跳过当前循环执行下一次语句。
package main
import (
"fmt"
"os"
"strings"
)
const corps = "lazy cat jumps again and again and again"
func main() {
words := strings.Fields(corps)
query := os.Args[1:]
querys:
for _, q := range query {
search:
for i, w := range words {
switch q {
case "and", "or", "the":
break search
}
if q == w {
fmt.Printf("#%-2d:find the words %q\n", i+1, w)
continue querys
}
}
}
}
Q5 路径搜寻,给定某个路径,判断是否在PATH路径中
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
)
func main() {
path := os.Getenv("PATH")
fmt.Println(path)
words := filepath.SplitList(path)
fmt.Println(words)
query := os.Args[1:]
for _, q := range query {
for i, w := range words {
q, w = strings.ToLower(q), strings.ToLower(w)
if strings.Contains(w, q) {
fmt.Printf("#%-2d:%q\n", i+1, w)
}
}
}
}
Q6 随机字符串,可以实现一个在缓冲等待的动态符号,这个我还是很喜欢
最后ctrl + c 结束该程序
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
var c string
for {
switch rand.Intn(4) {
case 0:
c = "\\"
case 1:
c = "/"
case 2:
c = "|"
case 3:
c = "-"
}
fmt.Printf("\r%s Please Wait. Processing....", c)
time.Sleep(time.Millisecond * 250)
}
}