我在Java中的程序有效,但我不確定如何獲得這兩個賬戶的總餘額。現在我只是打印出#####。如何在儲蓄賬戶程序中添加總計所有月份餘額的代碼
這應該是輸出:
兩個帳戶相結合的餘款:5255.81
我不想只需鍵入答案。我們必須展示程序添加兩個帳戶的所有餘額,但我不知道如何編寫該代碼。
這裏是我的司機:
public class LineberryRaeChapter13Prog {
public static void main(String args[])
{
LRSavingsAccount saver1 = new LRSavingsAccount(2000);
LRSavingsAccount saver2 = new LRSavingsAccount(3000);
LRSavingsAccount.newInterestRate(0.05);
System.out.println("\nMonthly balances for one year with 0.05 annual interest:\n");
System.out.printf("%10s%10s%10s%10s%10s\n", "Month", "Account#", "Balance", "Account#", "Balance");
System.out.printf("%10s%10s%10s%10s%10s\n", "-----", "--------", "-------", "--------", "-------");
System.out.printf("%10s%10s%10s%10s%10s\n", "0","10002", saver1.toString(), "10003", saver2.toString());
for (int month = 1; month <= 12; month++)
{
switch (month)
{
case 1:System.out.printf("\n");
break;
case 2:System.out.printf("\n");
break;
case 3:System.out.printf("\n");
break;
case 4:System.out.printf("\n");
break;
case 5:System.out.printf("\n");
break;
case 6:System.out.printf("\n");
break;
case 7:System.out.printf("\n");
break;
case 8:System.out.printf("\n");
break;
case 9:System.out.printf("\n");
break;
case 10:System.out.printf("\n");
break;
case 11:System.out.printf("\n");
break;
case 12:System.out.printf("\n");
break;
}//end switch
String monthLabel = String.format("%d", month);
saver1.addMonthlyInterest();
saver2.addMonthlyInterest();
System.out.printf("%10s%10s%10s%10s%10s\n", monthLabel, "10002", saver1.toString(), "10003", saver2.toString());
}//end for
System.out.printf("%10s%10s\n", "\nFinal balance of both accounts combined:", "######");
}//end main
}//end LineberryRaeChapter13Prog
這裏是類:
public class LRSavingsAccount
{
// interest rate for all accounts
private static double annualInterestRate = 0;
private double Balance;
public static void newInterestRate(double newRate)
{
annualInterestRate = (newRate >= 0 && newRate <= 1.0) ? newRate : 0.05;
}//end newInterestRate
// provides account balances
public LRSavingsAccount(double balance)
{
Balance = balance;
}//end Constructor
// calculates the interest for each month
public void addMonthlyInterest()
{
Balance += Balance * (annualInterestRate/12.0);
}//end addMonthlyInterest
// get string representation of SavingAccount
public String toString()
{
return String.format("$%.2f", Balance);
}//end accesssor
}//end SavingsAccount
爲LRSavingsAccount添加代碼。或者你可以使用Double.parseDouble(saver1.toString())+ Double.parseDouble(saver2.toString()) – StackFlowed
你還可以提供'LRSavingsAccount'的實現嗎?我認爲這會像'saver1.getBalance()+ saver2.getBalance()'一樣簡單,但我不知道是否有這樣的方法。 –
你必須編輯你的帖子並把類LRSavingsAccount。另外,你有什麼交易? –