Last active
May 9, 2017 16:16
-
-
Save BalicantaYao/781b12cbb0b1bf71cbf61059da63d23c to your computer and use it in GitHub Desktop.
類別建立 - 戶頭
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
s4.(戶頭) | |
實作一戶頭類別Account,內含私有餘額balance,型別實數, | |
對外提供如下公開方法: | |
public Account(double initialBalance) //建構子,含初始餘額 | |
public void credit(double amount) // 存款,含存款金額 | |
public double getBalance() // 讀出餘額,回傳餘額 | |
測試時,可用建構子建立一個戶頭,初始餘額為50,先印餘額看對不對, | |
再存入25,印餘額看對不對. | |
註: 建構子若遇初始餘額<0,可一律設定為0. | |
s5.(承上) | |
為戶頭類別新增如下提款方法: | |
public double debit(double amount) | |
// 自戶頭餘額扣掉amount金額,回傳實際扣掉金額 | |
// 若戶頭餘額不足,不作扣款,印出"餘額不足"訊息,回傳金額為0 | |
Account account = new Account(100); | |
// 印出初始金額 | |
// 存入 300 元 | |
// 印出當前餘額 | |
// 試圖提 600 元 印出餘額不足 | |
// 試圖提 200 元 印出提款 200 元 | |
// 印出餘額 | |
*/ |
`/**
- Created by Jason.Yao on 2017/5/5.
- 初始金額: 100.0
餘額: 100.0
存款:300.0 餘額等於:400.0
存款餘額:400.0 餘額不足:600.0
提款: 200.0
餘額: 200.0
*/
public class BackAccunt {
public static void main(String[] args) {
int tocash = 0;
System.out.print("初始金額: ");
Account account = new Account(100);
System.out.print("餘額:");
System.out.println(account.getBalance());
tocash = 300;
System.out.println("存款:" + tocash);
account.credit(tocash);
System.out.println("餘額等於" + account.getBalance());
tocash = 600;
double balance = account.getBalance();
if (tocash > balance) {
System.out.print("存款餘額:" + balance + " " + "餘額不足:");
System.out.println(account.debit(tocash));
} else {
balance = balance - tocash;
System.out.print("提款: ");
System.out.println(account.debit(tocash));
System.out.println(account.getBalance());
}
tocash = 200;
double balance1 = account.getBalance();
if (tocash > balance1) {
System.out.print("存款餘額:" + balance + " " + "餘額不足:");
System.out.println(account.debit(tocash));
} else {
balance1 = balance1 - tocash;
System.out.print("提款: ");
System.out.println(account.debit(tocash));
System.out.print("餘額:");
System.out.println(account.getBalance());
}
}
static class Account {
private double balance;
public Account(double initialBalnce){
if (initialBalnce <= 0) {
this.balance = 0;
System.out.println(this.balance);
}else{
this.balance = initialBalnce;
System.out.println(this.balance);
}
}
public void credit(double amount){
this.balance = this.balance + amount;
}
public double getBalance(){
return this.balance;
}
public double debit(double amount) {
return amount;
}
}
}`
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Homework
System.out.println
移出 Account