如何编码在储蓄帐户计划

时间:2015-09-11 19:23:36

标签: java

我的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

1 个答案:

答案 0 :(得分:1)

我看到它的方式你可以在LRSavingsAccount中为Balance字段添加一个getter。 所以

public double getBalance() { return Balance; }

最后,你可以做到

System.out.println(Final balance of both accounts combined:" + (saver1.getBalance() + saver2.getBalance());

除非我遗漏了什么。