// Chapter 30 example: a small command loop that uses package bank. // // Run from this folder: // cd exercises/30/02-account-package // go run . package main import ( "bufio" "fmt" "os" "strconv" "strings" "accountpackage/bank" ) var reader = bufio.NewReader(os.Stdin) // readLine prints the prompt and gives back one trimmed line. The error is // not nil when there is no more input. func readLine(prompt string) (string, error) { fmt.Print(prompt) text, err := reader.ReadString('\n') line := strings.TrimSpace(text) if err != nil && line == "" { return "", err } return line, nil } // doAmount runs "deposit" or "withdraw" with the amount the user typed. func doAmount(acc *bank.Account, verb string, amountText string) { amount, err := strconv.Atoi(amountText) if err != nil { fmt.Println("That is not a whole number.") return } if verb == "deposit" { err = acc.Deposit(amount) } else { err = acc.Withdraw(amount) } if err != nil { fmt.Println("Error:", err) return } fmt.Println("Balance:", acc.Balance()) } func main() { acc, err := bank.NewAccount("Keiko") if err != nil { fmt.Println("Error:", err) return } fmt.Println("Account for", acc.Owner()) for { line, err := readLine("> ") if err != nil { fmt.Println() fmt.Println("No more input.") return } words := strings.Fields(line) if len(words) == 1 && words[0] == "quit" { fmt.Println("Goodbye.") return } if len(words) == 1 && words[0] == "balance" { fmt.Println("Balance:", acc.Balance()) continue } if len(words) == 2 && (words[0] == "deposit" || words[0] == "withdraw") { doAmount(acc, words[0], words[1]) continue } fmt.Println("Commands: deposit , withdraw , balance, quit") } }