Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Let us analyze the following class: import java.util.Scanner; public class D4Tes

ID: 3558522 • Letter: L

Question

Let us analyze the following class:

import java.util.Scanner;

public class D4Test
{

      public static void main(String args[ ])
       {
          
            double annualSalary = 0.0;
            double weeklySalary = 0.0;

            Scanner sc = new Scanner(System.in);

            System.out.print("Please enter your annual salary: ");
            annualSalary = sc.nextDouble();

            weeklySalary = calculateWeeklyPay(annualSalary);

            System.out.println("Your weekly salary is: " + weeklySalary);

        } //end main


     public void calculateWeeklyPay(double inSal)
       {
             double inSal;

             return (inSal/52) ;
       }

    } //end class




(1) Please describe one bug that this class has. Why is it a bug? Please explain.

(2) Please describe how to fix it. Please include the corrected program code.

Explanation / Answer

1st bug is in this statement : weeklySalary = calculateWeeklyPay(annualSalary);

This is incorrect use and will throw an error saying "non-static method calculateWeeklyPay(double) cannot be referenced from a static context". This is because calculateWeeklyPay(double) method is defined inside D4Test class and can be called only by creating an instance of D4Test class. A method defined inside an class can be called only via an instance of the class. An exception is when the method is defined as "static", in which case it can be called directly without creating a class instance. So, this bug can be fixed in 2 ways :

1. Define calculateWeeklyPay method as static : public static double calculateWeeklyPay(double inSal)

2. Create a class instance and then call calculateWeeklyPay method

D4Test d = new D4Test();
weeklySalary = d.calculateWeeklyPay(annualSalary);

2nd bug in the code is the return type of calculateWeeklyPay() method. Instead of void it should be double.

3rd bug is re-declaration of an already defined variable inSal inside calculateWeeklyPay() method.

After fixing the above 3 bugs the code should look like this (changes in bold):

import java.util.Scanner;

public class D4Test

{

   public static void main(String args[ ])
   {
       double annualSalary = 0.0;
       double weeklySalary = 0.0;

       Scanner sc = new Scanner(System.in);

       System.out.print("Please enter your annual salary: ");
       annualSalary = sc.nextDouble();

       weeklySalary = calculateWeeklyPay(annualSalary);

       System.out.println("Your weekly salary is: " + weeklySalary);

   } //end main

   public static double calculateWeeklyPay(double inSal)
   {
       //double inSal;
       return (inSal/52) ;
   }

} //end class