对于每个循环设定值

时间:2016-03-12 00:58:12

标签: java for-loop foreach

遇到问题。我有两种方法for each循环计算高管按百分比或基本工资支付。在我的行政课程中,我的薪酬方法采用基本工资率并乘以奖金。这有效,如果它的百分比,但如果它的基本支付和调用这种方法不起作用。 我是否在我的高管班上发了一个if语句,看看它的百分比或基本工资是多少?

员工班级

/**
 * Assigns the specified flat value weekly bonus to the Executives.
 *
 * @param bonusValue
 *            as a double, i.e., $1,000 = 1000.0
 */

public void setExecutiveBonusFlatRate(double bonusValue) {
    for (StaffMember executiveEmployee : staffList) {
        if (executiveEmployee instanceof Executive) {
            ((Executive) executiveEmployee).setBonus(bonusValue);                         

        }
    }
}



/**
 * Assigns the specified percentage weekly bonus to the Executives.
 * 
 * @param bonus
 *            as a percentage, i.e., 20% = 0.2
 */

public void setExecutiveBonusPercentage(double bonusPercentage) {
    for (StaffMember executiveEmployee : staffList) {
        if (executiveEmployee instanceof Executive) {
            ((Executive) executiveEmployee).setBonus(bonusPercentage);

        }
    }   
}

/**
 * Pays all the staff members.
 */

public void payday() {
   for (StaffMember allEmployee : staffList) {
       allEmployee.toString();
       System.out.println(allEmployee.pay());
       System.out.println(allEmployee.toString());
   }
}

从Employee

扩展的Executive类
/**    @overide
 *  return the weekly payrate plus the bonus
 */

public double pay() { 

   double payment = payRate * bonus;
   bonus = 0;
   return payment;

1 个答案:

答案 0 :(得分:1)

我们需要在这里纠正两件事:

  1. setExecutiveBonusPercentage应将奖金设置为base * percentage * 0.01,以便与bonusValue中设置的setExecutiveBonusFlatRate保持一致,因为我们无法知道bonus是一个值或百分比。

  2. pay()方法中,我们将奖励设置为0(bonus = 0;),因为它会重置奖励值,因此需要将其删除。因此,pay()的第一次调用将返回正确的结果,而后续的调用将返回0.