Methods keep the rules of an object in one place.
What to build
A program that applies deposits and withdrawals to an account and reports problems.
Requirements
- Read n, then n commands. The account starts with a balance of 0.
deposit Xadds X.withdraw Xsubtracts X.balanceprintsbalance: B.- If X is not greater than 0, print
invalid amountand change nothing. If a withdrawal is larger than the balance, printinsufficient fundsand change nothing.
Input
Line 1: n. Then n commands, deposit X, withdraw X or balance.
Output
Messages as described.
Constraints
1 ≤ n ≤ 100; X is between -1000 and 1000.
Example
Input:
5
deposit 100
withdraw 30
withdraw 100
balance
deposit -5
Output:
insufficient funds
balance: 70
invalid amount
Why it works
The rules live in the methods, so main only reads commands. The methods use a pointer receiver because they change the balance.
Examples
Example 1 · Input
5 deposit 100 withdraw 30 withdraw 100 balance deposit -5
Expected output
insufficient funds balance: 70 invalid amount
Example 2 · Input
2 balance withdraw 0
Expected output
balance: 0 invalid amount
Hints
Hint 1
type Account struct { balance int } with methods Deposit(x int) string and Withdraw(x int) string that return the message to print.
Hint 2
Check the amount first (must be positive), then check the balance.
Solution
Show one correct solution (try it yourself first)
package main
import "fmt"
type Account struct {
balance int
}
func (a *Account) Deposit(x int) {
if x <= 0 {
fmt.Println("invalid amount")
return
}
a.balance += x
}
func (a *Account) Withdraw(x int) {
if x <= 0 {
fmt.Println("invalid amount")
return
}
if x > a.balance {
fmt.Println("insufficient funds")
return
}
a.balance -= x
}
func main() {
var n int
fmt.Scan(&n)
var a Account
for i := 0; i < n; i++ {
var cmd string
fmt.Scan(&cmd)
switch cmd {
case "deposit":
var x int
fmt.Scan(&x)
a.Deposit(x)
case "withdraw":
var x int
fmt.Scan(&x)
a.Withdraw(x)
case "balance":
fmt.Println("balance:", a.balance)
}
}
}