2014-08-31 2 views
0

저는 처음 1 년 동안 Java를 배우는 학생이며 "은행에 총 돈을 돌려주는 방법을 만드시겠습니까?"라고 질문했습니다. 시험에서. 아래에 수업을 포함 시켰습니다. addAccount(), getBalance(), withdraw() 등 대부분의 메소드가 올바르지 만이 답변이 무엇인지 확실하지 않았습니다. 이것은 아마도 (내가 for 루프 나 어떤 종류의 두 가지를 사용해야 만한다는) 생각보다 간단하고 간단하지만 합계를 더하는 정확한 방법을 명확히하기 위해서입니다. 이것은 또한 고객이 과일 야채 등 다른 제품에서 제품을 구입하고 총계를 계산해야하는 식료품 점에 대한 C# 지정에서 나온 것입니다. 슈퍼 클래스 :은행 계좌 합계를 찾으십시오.

/** 
    A bank account has a balance that can be changed by 
    deposits and withdrawals. 
*/ 
public class BankAccount 
{ 
    //Declare balance field 
    private double balance; 

    /** 
     Constructs a bank account with a zero balance. 
    */ 
    public BankAccount() 
    { 
     balance = 0; 
    } 

    /** 
     Constructs a bank account with a given balance. 
     @param initialBalance the initial balance 
    */ 
    public BankAccount(double initialBalance) 
    { 
     balance = initialBalance; 
    } 

    /** 
     Deposits money into the bank account. 
     @param amount the amount to deposit 
    */ 
    public void deposit(double amount) 
    { 
     balance = balance + amount; 
    } 

    /** 
     Withdraws money from the bank account. 
     @param amount the amount to withdraw 
    */ 
    public void withdraw(double amount) 
    { 
     if (balance >= amount) 
     { 
     balance = balance - amount; 
     } 
     else 
     { 
      System.out.println("Withdrawal error: insufficent funds"); 
     } 
    } 

    /** 
     Gets the current balance of the bank account. 
     @return the current balance 
    */ 
    public double getBalance() 
    { 
     return balance; 
    } 

    /** 
     Transfers money from the bank account to another account 
     @param amount the amount to transfer 
     @param other the other account 
    */ 
    public void transfer(double amount, BankAccount other) 
    { 
     withdraw(amount); 
     other.deposit(amount); 
    } 

    public String toString() 
    { 
     return "Your Balance: "+ balance; 
    } 
} 

서브 클래스 당좌 예금 계좌 :

/** 
    A checking account that charges transaction fees. 
*/ 
public class CheckingAccount extends BankAccount 
{ 
    private int transactionCount; 
    private int transaction; 

    private static final int FREE_TRANSACTIONS = 0; 
    private static final double TRANSACTION_FEE = 2.0; 

    /** 
     Constructs a checking account with a given balance. 
     @param initialBalance the initial balance 
    */ 
    public CheckingAccount(double initialBalance) 
    { 
     // Construct superclass 
     super(initialBalance); 

     // Initialize transaction count 
     transactionCount = 0; 
    } 

    public void deposit(double amount) 
    { 
     transactionCount++; 
     // Now add amount to balance 
     super.deposit(amount); 
    } 

    public void withdraw(double amount) 
    { 
     transactionCount++; 
     // Now subtract amount from balance 
     super.withdraw(amount); 
    } 

    /** 
     Deducts the accumulated fees and resets the 
     transaction count. 
    */ 
    public void deductFees() 
    { 
     if (transactionCount > FREE_TRANSACTIONS) 
     { 
     double fees = TRANSACTION_FEE * 
       (transactionCount - FREE_TRANSACTIONS); 
     super.withdraw(fees); 
     } 
     transaction = transactionCount; 
    } 

    public String toString() 
    { 

     return super.toString() + "\t Your Transactions: "+ transaction; 
    } 

} 

서브 클래스의 예금 계좌 :

폴에게 ... 사전에

코드를 주셔서 감사합니다

/** 
    An account that earns interest at a fixed rate. 
*/ 
public class SavingsAccount extends BankAccount 
{ 
    private double interestRate; 

    /** 
     Constructs a bank account with a given interest rate. 
     @param rate the interest rate 
    */ 
    public SavingsAccount(double rate) 
    { 
     interestRate = rate; 
    } 

    /** 
     Constructs a bank account with a given interest rate. 
     @param rate the interest rate 
    */ 
    public SavingsAccount(double rate, double initBalance) 
    { 
     super(initBalance); 
     interestRate = rate; 
    } 

    /** 
     Adds the earned interest to the account balance. 
    */ 
    public void addInterest() 
    { 
     double interest = getBalance() * interestRate + 100; 
     deposit(interest); 
    } 

     public String toString() 
    { 

     return super.toString() + "\t Your Interest rate: "+ interestRate; 
    } 

} 

답변

0

당신 말이 맞습니다.

BankAccount 또는 하위 클래스 모음이있는 경우 for 루프에서 간단히 합계 할 수 있습니다. 나는에 getBalance() 메소드를 기대

Collection<BankAccount> accounts = Bank.getAccounts(); 
Double sum = 0.0; 
for (BankAccount account : accounts) { 
    sum += account.getBalance(); 
} 
+0

그 분들께 감사 드리며 엉망으로 샘플 코드를 제공해 주신 것을 기쁘게 생각합니다. 나는 올바른 방향에 있다는 것을 알게되어 기쁩니다. 그러나 두 번째 의견을 가지고있는 것이 좋습니다. – Paul66

+0

그런 다음 답변을 수락하십시오 ;-) – mcdikki

0

루프에 대해 생각하고 있습니다. 잔금을 합산하십시오.

public static double totalBalance(Collection<BankAccount> accounts){ 
    double sum = 0.0; 
    for(BankAccount b : accounts){ 
     sum += b.getBalance(); 
    } 
    return sum; 
} 
+0

흠 :

는 (내가 어떤 식 으로든 나에게 모든 계정을 제공하는 기능을 포함하는 은행 객체가 있다고 가정)이 같은 뭔가를 말할 수 있습니다 항상 계정에 올바른 balnce가 생기고 addContent() 및 dectutFees() 메소드가 Bankcontroler에서 자주 호출하게됩니다. 잔액을 확인할 때마다 사용하면 잔액이 변경되고 잔액은 체크 한 횟수에 따라 달라집니다. 이것은 나에게 잘못된 것 같습니다 ... – mcdikki

+0

아마 맞을 것입니다. deductFees()를 호출하면 트랜잭션이 더 이상 남아 있지 않으면 잔액이 변경되지 않으므로 종종 상처를주지는 않습니다. 그러나 addInterest는 마지막으로 호출 된 이후로 경과 한 "시간"에 관계없이 항상 동일한 양의 관심을 추가한다는 것을 알게되었습니다. 나는 그 부분을 제거 할 것이다. – Mshnik

관련 문제