gpt4 book ai didi

java - 如何编写代码添加储蓄帐户程序中所有月份余额的总计

转载 作者:行者123 更新时间:2023-11-30 07:57:00 26 4
gpt4 key购买 nike

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

这是类(class):

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”中为“余额”字段添加一个 getter。所以

公共(public)双 getBalance() {
返回余额;
}

最后,你可以这样做

System.out.println(两个账户的最终余额合计:"+ (saver1.getBalance() + saver2.getBalance());

除非我错过了什么。

关于java - 如何编写代码添加储蓄帐户程序中所有月份余额的总计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32530768/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com