復習 - 銀行口座管理
CoddyのGDScriptジャーニー「オブジェクト指向プログラミング」セクションの一部。レッスン 14/65。
チャレンジ
中級bank_account.gdにクラスBankAccountを記述してください。このクラスでは、この章で学んだ内容をすべて組み合わせます。
- すべての口座で共有される、初期値が
2の静的なint変数interest_percent - 2つのプライベートプロパティ:
_owner_name(String)と_balance(初期値が0のint) - ゲッターが
_owner_nameを返す読み取り専用プロパティowner_name - ゲッターが
_balanceを返すプロパティbalance。セッターは負の値の場合にBalance cannot be negativeを出力し、それ以外の場合は値を_balanceに保存します - コンストラクター
_init(account_owner, start_balance)は所有者を保存し、start_balanceをbalanceに代入します。これにより、セッターで値がチェックされます
さらに、次のメソッドを作成してください。
deposit(amount):amountが0以下の場合はDeposit amount must be positiveを出力してfalseを返します。それ以外の場合は金額を加算してtrueを返しますwithdraw(amount):amountが0以下の場合はWithdrawal amount must be positiveを出力してfalseを返し、残高を超える場合はInsufficient fundsを出力してfalseを返します。それ以外の場合は金額を差し引いてtrueを返しますapply_interest():_balance * interest_percent / 100(ドル単位の整数)を残高に加算し、その利息額を返しますdisplay_info():Account Owner: NAME、Balance: $BALANCE、Interest Rate: PERCENT%の3行を出力します
用意されているコードは、owner start_balance、続くコマンドの数、およびdeposit N、withdraw N、set N(balanceに代入)、interest、rate N(BankAccount.interest_percentを設定)、infoの各コマンドを読み込みます。入金、出金、利息の支払いが成功するたびに1行を出力し、最後に所有者の残高を出力します。Coddy 1000と、コマンドdeposit 500、withdraw 200、interest、info、set 5000、withdraw 10000を入力すると、次のように出力されます。
Deposited $500
Withdrew $200
Interest earned: $26
Account Owner: Coddy
Balance: $1326
Interest Rate: 2%
Insufficient funds
Coddy has $5000コードはbank_account.gdに記述してください。main.gdには用意されている入出力コードが含まれており、編集できません。
自分で試してみよう
extends Node
func _ready():
# 用意された入出力コード: そのままにしてください
var first := OS.read_string_from_stdin().split(" ")
var account := BankAccount.new(first[0], int(first[1]))
var count := int(OS.read_string_from_stdin())
for i in count:
var parts := OS.read_string_from_stdin().split(" ")
match parts[0]:
"deposit":
if account.deposit(int(parts[1])):
print("Deposited $%s" % parts[1])
"withdraw":
if account.withdraw(int(parts[1])):
print("Withdrew $%s" % parts[1])
"set":
account.balance = int(parts[1])
"interest":
print("Interest earned: $%d" % account.apply_interest())
"rate":
BankAccount.interest_percent = int(parts[1])
"info":
account.display_info()
print("%s has $%d" % [account.owner_name, account.balance])
オブジェクト指向プログラミングのすべてのレッスン
自分で練習してみよう: GDScriptオンラインコンパイラ