我需要做的是提示用户提供本金,利率和期限。然后用户选择数月或数年。
我不知道如何使用for循环计算复合月利率。我已经在线查看了公式,但每当我尝试将其翻译成java代码时,我都会失败。
我知道我需要除以12,但在循环中我的利息和本金金额一直变小,直到0.有人可以帮忙吗? ty
public Calculator()
{
Scanner input = new Scanner(System.in);
boolean error = false;
while (!error){
System.out.print("Please input the following: principal, interest rate, term >> ");
double principal = input.nextDouble();
double interest_rate = input.nextDouble();
int term = input.nextInt();
String MonthOrYear = input.next();
int termInMonths = term * 12;
char dollar_sym = 36;
if (interest_rate <= 0 || term <= 0 || principal <= 0)
{
System.out.println("The term, interest rate and principal must be greater than zero");
continue;
}
if (!MonthOrYear.equals("month") && (!MonthOrYear.equals("year")&&
(!MonthOrYear.equals("Month")&& (!MonthOrYear.equals("Year") && (!MonthOrYear.equals("years")
&& (!MonthOrYear.equals("months") && (!MonthOrYear.equals("Years") &&
(!MonthOrYear.equals("Months")))))))))
{
System.out.println("Please input either month or year after term");
continue;
}
System.out.println("Month: " + " Interest: " + "Principal: ");
if (MonthOrYear.equals("month") || (MonthOrYear.equals("Months") || (MonthOrYear.equals("Month")
|| (MonthOrYear.equals("months")))))
{
for (int month = 1; month <= term; month++)
{
double interest = principal * interest_rate / 100;
principal = principal + interest;
System.out.printf("%4d %c%5.2f %c%5.2f\n", month, dollar_sym, interest, dollar_sym, principal );
}
}
else if (MonthOrYear.equals("year") || (MonthOrYear.equals("Years") || (MonthOrYear.equals("Year")
|| (MonthOrYear.equals("years")))))
{
for (int month = 1; termInMonths >= month; month++)
{
double interest = principal * interest_rate / 100;
principal = principal + interest;
System.out.printf("%4d %c%5.2f %c%5.2f\n", month, dollar_sym, interest, dollar_sym, principal );
}
}
break;