206k views
1 vote
The following program uses a variable workHoursPerWeek rather than directly using 40 in the salary calculation expression.

Run the program, observe the output. Change 40 to 35 (France's work week), and run again.

Generalize the program further by using a variable workWeeksPerYear. Run the program. Change 50 to 52, and run again.

Introduce a variable monthlySalary, used similarly to annualSalary, to further improve program readability.

public class Salary {
public static void main (String [] args) {
int hourlyWage = 20;
int workHoursPerWeek = 40;
// FIXME: Define and initialize variable workWeeksPerYear, then replace the 50's below
int annualSalary = 0;

annualSalary = hourlyWage * workHoursPerWeek * 50;
System.out.print("Annual salary is: ");
System.out.println(annualSalary);

System.out.print("Monthly salary is: ");
System.out.println((hourlyWage * workHoursPerWeek * 50) / 12);

return;
}
}

User Gary Riley
by
4.2k points

1 Answer

2 votes

Answer:

Initial program output (from original program)

Annual salary is: 40000

Monthly salary is: 3333

Program output after workHoursPerWeek = 35

Annual salary is: 35000

Monthly salary is: 2916

Revised program (using variable workWeeksPerYear)

  1. public static void main(String[] args) {
  2. int hourlyWage = 20;
  3. int workHoursPerWeek = 35;
  4. int workWeeksPerYear = 52;
  5. int annualSalary = 0;
  6. annualSalary = hourlyWage * workHoursPerWeek * workWeeksPerYear;
  7. System.out.print("Annual salary is: ");
  8. System.out.println(annualSalary);
  9. System.out.print("Monthly salary is: ");
  10. System.out.println((hourlyWage * workHoursPerWeek * workWeeksPerYear) / 12);
  11. return;
  12. }

Program output:

Annual salary is: 36400

Monthly salary is: 3033

Revised Program after introducing monthly salary

  1. public static void main(String[] args) {
  2. int hourlyWage = 20;
  3. int workHoursPerWeek = 35;
  4. int workWeeksPerYear = 52;
  5. int annualSalary = 0;
  6. int monthlySalary = 0;
  7. annualSalary = hourlyWage * workHoursPerWeek * workWeeksPerYear;
  8. monthlySalary = hourlyWage * workHoursPerWeek * workWeeksPerYear;
  9. System.out.print("Annual salary is: ");
  10. System.out.println(annualSalary);
  11. System.out.print("Monthly salary is: ");
  12. System.out.println((monthlySalary) / 12);
  13. return;
  14. }

Step-by-step explanation:

One reason to use variable to replace the magic number is to improve the readability of the program. If we compared the revised version of the program with the original program, we will find that the variable enable our code easier to understand.

Besides, if we wish to change the value (e.g. working hours per year or per month), we just need to adjust the value assigned on the variables. The variables provide a single access point to get or change the value.

User Nat Kuhn
by
4.4k points