如何将循环中计算的月薪汇总为Java中的年薪

时间:2018-09-11 07:50:34

标签: java for-loop io sum

我采用了for循环,根据两个因素计算每个月的薪水:固定薪金$ 50000和每月加班的额外时薪$ 550。后一个变量显然每个月都会变化,因此我采用了扫描器类来接收每月的输入。 (在我的循环之前,所有必需的参数都已充分定义) 我的循环看起来像这样:

    for(int month = 1; month <= 12; month++){

        System.out.print("How many extra hours did you work this month?");
        double extraHoursPerMonth = scan.nextInt();

        double bonusSalary = extraHoursPerMonth*bonusSalaryPerHour;
        double totalMonthlySalary = basicSalary + bonusSalary;

        System.out.println("Your salary for this month is $" + totalMonthlySalary);

运行时,成功计算每个月的总薪水。那我该如何找到年薪呢?

我找不到我可以使用的任何代码来总结一下,以前计算出的月薪最终是一笔总和,我感觉自己好像是在砖墙上。我将不胜感激关于前进的任何指针,暗示或建议。

2 个答案:

答案 0 :(得分:0)

您将必须在for循环外创建一个变量,并为每次迭代加总月薪,例如

int annualSalary = 0;
  for(int month = 1; month <= 12; month++){

    System.out.print("How many extra hours did you work this month?");
    double extraHoursPerMonth = scan.nextInt();

    double bonusSalary = extraHoursPerMonth*bonusSalaryPerHour;
    double totalMonthlySalary = basicSalary + bonusSalary;

    System.out.println("Your salary for this month is $" + 
    totalMonthlySalary);
  }
  System.out.println("Your annul salary for this year is $" + annualSalary);

答案 1 :(得分:0)

如果想要年薪,可以通过将月薪乘以12来获得。

double anualSalary = basicSalary*12;

如果您希望获得总薪水,则应在 anualSalary 声明之后和for循环之前声明一个变量。

double overalSalary = anualSalary;

然后在for循环的每个循环中添加奖金。

...
overalSalary += bonusSalay;
...