我有一个方法compute(int months),但它不会像我想要的那样进行迭代

时间:2019-03-07 04:40:24

标签: java loops iteration

这是我的方法compute(),需要几个月的时间:

 public double compute(int months){
        double balance = employee.getSalary();
        double newBalance=0;
        double monthlyInterest = (bankName.getInterestRate())/12;
        double annualRaise = employee.getAnnualRaise();

if (months <=12){
      for (int i = 1; i <= months; i++){
        newBalance = (newBalance+balance)*(1+monthlyInterest);
      }
      return newBalance;
    }

    else{

      int cycle = months/12;

      while (cycle >0){
        for (int i = 1; i <= 12; i++){
          newBalance = (newBalance+balance)*(1+monthlyInterest);
        }
        cycle--;

        months = months - 12; //remainder of months

        balance = balance*(1+annualRaise/100); //new starting salary

      }

      for (int k = 1; k <= months; k++){
        newBalance = (newBalance+balance)*(1+monthlyInterest);
      }
      return newBalance;
    }

  }

要提供上下文,

  1. 余额:员工每月在月初获得的固定月薪
  2. 每月利息:是根据员工银行每月余额计算的利率
  3. 年度加薪:是新年开始时员工月薪的加薪

我输入的示例如下:

Bill Jobs 54000.0 0 0.012 13

其中,比尔·乔布斯(Bill Jobs)是一名雇员,其余额为54K,每年加薪0%,每年从银行获得的年利率为1.2%,计算时间将超过13个月。我想要的输出应该是:

Bill Jobs: salary is 54K, annual raise is 0% has balance of 706933.71 

当我调用compute方法时,会计算出余额706933.71,但是最终我得到了

Bill Jobs: salary is 54K, annual raise is 0% has balance of 705852.63

他13个月后的余额改为705852.63。

1 个答案:

答案 0 :(得分:0)

请参阅以下基本计算,以计算每月加息1.5%的工资。您可以根据需要进行修改。

import java.util.Scanner;

public class Salary {

public static void main(String[] args) {

    double salary = 24000;
    double interest = 1.5;
    double total = 0;
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the month = ");
    int month = sc.nextInt();
    if(month != 0 && month  < 13){
        for(int i=1; i <= month; i++){
            salary += total;
            total = (salary + (salary * (interest/100)))  ;
        }
        System.out.println("salary with interest "+total);
    }else{
        System.out.println("Enter the month from 1-12");
    }


   }

}