Page 1 of 2 12 LastLast
Results 1 to 20 of 22
  1. #1
    ethemartian is offline Member
    Join Date
    Feb 2011
    Posts
    15
    Rep Power
    0

    Default Please help with mutator

    Hi, Im taking my first java programming class! (yay!) Im having trouble implementing a mutator that adds 2 variables, bonus and salary. Here are the instructions from the professor:


    Implement a class called Employee. An employee has a name and gets a salary. Every pay period each employee gets an additional amount in bonus.

    Include a constructor that accepts the name and salary of an employee. Provide a mutator method that accepts the bonus amount and adds it to the salary. Provide necessary accessor methods to return each field value.

    Heres what my code looks like so far:

    public class Employee
    {
    private String name;
    private double salary, bonus;

    public Employee(String nme, double slry, double bns)
    {
    name=nme;
    salary=slry;
    bonus=bns;
    }

    public String getNme()
    {
    return name;
    }

    public double getSlry()
    {
    return salary;
    }

    public double getBns()
    {
    return bonus;
    }

    public void getSlry (double slry)
    {
    salary = slry;
    }
    public double AddSalary()
    {
    return salary + bonus;
    }
    }


    And here is what my test class looks like so far:

    class TestEmployee
    {
    public static void main(String[] args)
    {
    Employee e1 = new Employee("Luis Navarro", 45000, 1000);
    Employee e2 = new Employee("John Doe", 35000, 800);
    System.out.println("ABC Payroll");
    report(e1);
    report(e2);

    System.out.println("----------- Report End -----------");
    }
    public static void report(Employee e)
    {
    System.out.println("------------ Employee ------------");
    System.out.println("Employee name : " + e.getNme());
    System.out.println("Salary before bonus: $" + e.getSlry());
    System.out.println("Bonus amount: "+"\t"+"$" +e.getBns());
    System.out.println("Salary after bonus : $" + e.AddSalary());

    }

    }

    I dont quite understand mutators well and even though I get the output I want, Im almost quite sure its not what the professor wants, how do you get the output of a mutator out when your calling it in the test class?

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    Im almost quite sure its not what the professor wants

    Accessor: a method that asks an instance for some piece information. It gets things - it accessess the instance the way a person would pick up their piggybank to estimate by weight the total savings.

    Mutator: a method that tells an instance some piece of information. It sets things - it mutates (changes) the instance the way a person would change their total savings by dropping a coin into their piggybank.

    Notice how different they are. An accessor doesn't give the piggybank anything. It gets information. From the piggybank's point of view the accessor doesn't have any arguments (it's not given anything) but it does have a return statement. In Java we use double etc to say what a method returns.

    A mutator is the opposite. From the piggybank's point of view the mutator will have an argument (it is given something) but it returns nothing. In Java we use "void" to say that nothing is being returned.

    In code:

    Java Code:
    class Piggybank {
        double balance;
    
        public Piggybank(double balance) {
            this.balance = balance;
        }
    
            // A typical accessor (or getter)
            // It has no arguments, but it returns something
        public double getBalance() {
            return balance;
        }
    
            // A typical mutator
            // It has an argument, but it returns nothing.
        public void updateBalance(double amount) {
            balance += amount;
        }
    }

    See if you can rewrite your accessors/mutators to conform to this pattern no-args-but-returns/has-args-but-doesn't-return-anything.

    ---------------------------

    Your professor doesn't actually say that bonus should be considered as a field. I would limit the accessors to name and salary. These would be the only arguments to the constructor (as the questiuon actually states).

    The role of bonus is as an argument for the mutator (which increases salary by this amount).

    I admit that this stretches the meaning of "bonus" which is not usually meant to denote a permanent change in salary.

    But that is what a mutator does: it changes things. And the question states the "mutator method [...] accepts the bonus amount and adds it to the salary". At best poorly worded.

    ------------------------------

    A second interpretation would be to have three fields (name/salary/currentBonus) and have the mutator set the value of currentBonus. There would be three or four accessors one each for name, salary, bonus and maybe total (which would return salary+currentBonus).

    This would be more in line with what a bonus is. But it flys in the face of your assignment's statement that the mutator adds something to the salary. In this case it would not: the accessor would in the course of figuring out the payment for the current month, or the test class would.

    Perhaps the professor could clarify - or pick one interpretation and run with it. The question as posted is badly worded.

    [edit] changed the piggybank metaphor because the accessor was a little too violently mutational.
    Last edited by pbrockway2; 02-05-2011 at 07:25 PM.

  3. #3
    ethemartian is offline Member
    Join Date
    Feb 2011
    Posts
    15
    Rep Power
    0

    Default

    pbrockway2 - The concept now makes alot more sense! But how does the mutator know what amount means If I have not specified it? for example if I take bonus off from the fields and input a mutator to get salary after bonus,

    public void AddBonus(double amount)
    {
    salary = salary + amount
    }

    How do you tell the mutator what amount it is that should be added?

    Thanks for the quick reply! Much appreciated!

  4. #4
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    How do you tell the mutator what amount it is that should be added?

    That happens in the test class. But notice the mutator does not "get salary after bonus": any getting is the business of an accessor.

    Java Code:
    System.out.println(e2.getSalary());  prints 35000
    e2.addBonus(800);
    System.out.println(e2.getSalary());  prints 35800

    This will increase e2's salary by $800.

    Was the test class given to you? If so it suggests bonus should be a field, the mutator should set the value of that field and the class given 4 accessors (ie option 2 in my previous post).

  5. #5
    ethemartian is offline Member
    Join Date
    Feb 2011
    Posts
    15
    Rep Power
    0

    Default

    No the test class was made by me, thats why it lists bonus as a field, I couldn't figure out the mutator/accessors part. So then I need to make a mutator that adds the bonus to the salary, and then build an accessor that gets what the mutator added? ie.

    public void AddBonus(double amount)
    {
    totalsalary = salary + amount;
    }

    public double gettotalsalary()
    {
    return totalsalary
    }

    Then for the test class:

    Employee 1:
    System.out.println("Bonus amount: "+"\t"+"$" +e.addbonus(1000));
    System.out.println("Salary after bonus : $" + e.gettotalsalary());

    Employee 2:
    System.out.println("Bonus amount: "+"\t"+"$" +e2.addbonus(800));
    System.out.println("Salary after bonus : $" + e2.gettotalsalary());
    Last edited by ethemartian; 02-05-2011 at 08:10 PM. Reason: Typo

  6. #6
    ethemartian is offline Member
    Join Date
    Feb 2011
    Posts
    15
    Rep Power
    0

    Default

    Got it to work, Here is my new code:

    Java Code:
    public class Employee
    {
        private String name;
        private double salary;
     
        public Employee(String nme, double slry)
        {
            name=nme;
            salary=slry;
        }
        public String getNme()
        {
            return name;
        }
        public double getSlry()
        {
            return salary;
        }
        public void AddBonus (double amount)
        {
        salary = salary + amount;
        }
    }
    And the test class:

    Java Code:
    class TestEmployee
    {
        public static void main(String[] args)
        {
            Employee e1 = new Employee("Enrique Teran", 45000);
            Employee e2 = new Employee("John Doe", 65000);
        System.out.println("ABC Payroll");
        report(e1);
        System.out.println("------------ Employee ------------");
        report2(e2);
    
        System.out.println("----------- Report End -----------");
        }
        public static void report(Employee e1)
        {
        System.out.println("------------ Employee ------------");
        System.out.println("Employee name      : " + e1.getNme());
        System.out.println("Salary before bonus: $" + e1.getSlry());
        e1.AddBonus(1000);
        System.out.println("Bonus amount: "+"\t"+"$" +"1000");
        System.out.println("Salary after bonus : $" + e1.getSlry());
        }
    
        public static void report2(Employee e2)
        {
        System.out.println("Employee name      : " + e2.getNme());
        System.out.println("Salary before bonus: $" + e2.getSlry());
        e2.AddBonus(800);
        System.out.println("Bonus amount: "+"\t"+"$" +"800");
        System.out.println("Salary after bonus : $" + e2.getSlry());
    
        }
    
    }
    I couldn't get it to accept e2. without creating report2, what did I do wrong?

    Moderator Edit: Code tags added
    Last edited by Fubarable; 02-05-2011 at 08:57 PM. Reason: Moderator Edit: Code tags added

  7. #7
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    That's not exactly my option 2 - but, if anything, it's better.

    But, please, remember addBonus() does NOT return anything. It's a mutator. (Think piggybanks. When you add() or set() or put(), do you get anything back? No! The fat little bugger just sits there and smiles.)

    So, in code:

    Java Code:
    Employee e = new Employee("Luis Navarro", 45000);
    e.addBonus(1000);
    
    //...
    
    System.out.println("Salary before bonus : $" + e.gettotalsalary());
    //System.out.println("Bonus amount: "+"\t"+"$" +e.addbonus(1000));
    // NO!  addBonus() does not return anything to print!
    // If you want you could say
    System.out.println("Bonus amount: "+"\t"+"$" +(e.getTotalSalary()-e.getSalary()));
    System.out.println("Salary after bonus : $" + e.gettotalsalary());

    -------------------------------------------

    Another point. I have decided to make 2011 the year of Java Naming Standards, so...

    Remember that classes start with a capital letter and methods and variables start with lowercase letters. Use camelCase if multiple words are involved. Adopting this habit will make your code more readable to yourself and others.

    So, totalSalary, getTotalSalary() etc.

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    What happens if you get rid of report2 method code and just pass the e2 object into the report method when you call it?

    Java Code:
    report(e1);
    report(e2);

    The key is that the parameter variable names don't matter, and you could name the variable in the method foo or bar if you want and it would still work with passing an e1 or e2 object into it.

    In other words, this would work fine in your program as your report method:

    Java Code:
    public static void report(Employee spam)
    {
      System.out.println("------------ Employee ------------");
      System.out.println("Employee name : " + spam.getNme());
      System.out.println("Salary before bonus: $" + spam.getSlry());
      spam.AddBonus(1000);
      System.out.println("Bonus amount: "+"\t"+"$" +"1000");
      System.out.println("Salary after bonus : $" + spam.getSlry());
    }

    because the parameter variable name doesn't matter to the rest of the program; it only matters inside the method itself. You could then call this report method with e1 or e2 being passed into it as I show above.


    Also, when posting code here, please use code tags so that your code will retain its formatting and thus will be readable -- after all, your goal is to get as many people to read your post and understand your code as possible, right?

    To do this, highlight your pasted code (please be sure that it is already formatted when you paste it into the forum; the code tags don't magically format unformatted code) and then press the code button, and your code will have tags.

    Another way to do this is to manually place the tags into your code by placing the tag [code] above your pasted code and the tag [/code] below your pasted code like so:

    Java Code:
    [code]
      // your code goes here
      // notice how the top and bottom tags are different
    [/code]
    Luck!
    Last edited by Fubarable; 02-05-2011 at 08:56 PM.

  9. #9
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    Our posts crossed. I'm gald you've got thing compiling and running.

    Personally I prefered what you had posted before with a totalSalary.

    I couldn't get it to accept e2. without creating report2, what did I do wrong?

    Your report() method shouldn't know or care which employee it is reporting on. The whole idea of having methods like this is to eliminate duplicated code. Unfortunately the way you have it set up now you can't use the trick I posted above of getting bonus by subtracting the two salary amounts. You would have to pass this to the report() method.

    Java Code:
    public static void report(Employee e, double bonus)
    {
        System.out.println("Employee name : " + e.getNme());
        System.out.println("Salary before bonus: $" + e.getSlry());
        e.AddBonus(bonus);
        System.out.println("Bonus amount: "+"\t"+"$" +bonus);
        System.out.println("Salary after bonus : $" + e.getSlry());
    }

    This will wrok, but it feels slightly odd to have a report() method both reporting AND adding a bonus. One method should do one thing. Again, I prefer how you had things before with a totalSalary field in the employee class that was mutated by addBonus(). If you do that, all the bonus adding can all be done before report() as you did originally.
    Last edited by pbrockway2; 02-05-2011 at 09:05 PM.

  10. #10
    ethemartian is offline Member
    Join Date
    Feb 2011
    Posts
    15
    Rep Power
    0

    Default

    Thanks for the tips! All very good, its too bad I cant just:

    Java Code:
    public static void report(Employee e1, e2)
    {
    then call up all the methods for e1 and e2
    That would make life alot easier!

  11. #11
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Quote Originally Posted by ethemartian View Post
    Thanks for the tips! All very good, its too bad I cant just:

    Java Code:
    public static void report(Employee e1, e2)
    {
    then call up all the methods for e1 and e2
    That would make life alot easier!
    No it wouldn't. Please re-read pbrockway's and my posts to see why.

  12. #12
    ethemartian is offline Member
    Join Date
    Feb 2011
    Posts
    15
    Rep Power
    0

    Default

    Ahh I see to delete duplicated code, my professor also keeps mentioning this!

  13. #13
    ethemartian is offline Member
    Join Date
    Feb 2011
    Posts
    15
    Rep Power
    0

    Default New Problem

    In another exercise the professor is giving me:
    Write a Java program that can be used to calculate the weekly salary for hourly paid employees. The program initially accepts the employee’s id, the number of hours worked, and the hourly pay rate. An employee may work additional hours. When this happens, the additional number of hours must be added to the original amount, and the salary is re-calculated. The program must output on separate lines the employee’s id number, the number of hours worked, the hourly pay rate, and the salary, for each employee. In addition, the program must also output the total amount of money paid out by the company.
    I got everything to work nicely but when it comes to mutating the employee's 1 hours by 10 its not giving me the correct amount. What it is doing is adding the total salary of employee 1 + 10 instead of hours of employee 1 + 10. Heres my code:

    Java Code:
     public void increaseHours(double amount)
        {
            hours += amount;
        }
    And the test: (Professor gave us this one)
    Java Code:
        System.out.println("\tIncrease " + employee1.getEmployeeId() + " by 10 hours");
        employee1.increaseHours(10); // 10 hours increase
        displaySalary(employee1, nf);
        // Re-calculate the salary and print
    What am I doing wrong?!?!

    the output comes out as 760 hours worked which reflects salary (750+10) when it should read 30(initial hours worked)+10= 40
    Last edited by ethemartian; 02-05-2011 at 11:31 PM.

  14. #14
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    You've got a bug elsewhere in your program in code you're not showing us. I'm guessing you're setting hours to the salary somewhere, but without code, I can't tell.

    As an aside, please don't post quotes in code tags as this makes it very difficult for us to see what your professor told you to do in your post above.. Use quote tags instead.

  15. #15
    ethemartian is offline Member
    Join Date
    Feb 2011
    Posts
    15
    Rep Power
    0

    Default

    Sorry I didnt know, Its fixed, Heres the full code:
    Java Code:
    public class Payroll
    {
        private String id;
        private double hours, rate;
    
        private static double TotalPayout;
    
    
        public Payroll(String EmployeeId, double EmployeeHours, double EmployeeRate)
        {
            id = EmployeeId;
            hours = EmployeeHours;
            rate = EmployeeRate;
    
            TotalPayout = TotalPayout + 0;
    
        }
    
        public static double getTotalPayout()
        {
            return TotalPayout;
        }
    
        public String getEmployeeId()
        {
            return id;
        }
        public double getEmployeeHours()
        {
            return hours;
        }
        public double getEmployeeRate()
        {
            return rate;
        }
        public double calculateSalary()
        {
            return  hours *= rate;
        }
        public void increaseHours(double amount)
        {
            hours += amount;
        }
    
    
    }
    And the test:

    Java Code:
    import java.util.Date; // Used for creating a Date object
    import java.text.DateFormat; // Used for specifying the format of the date
    import java.text.NumberFormat; // Used for specifying the type of currency
    
    class TestPayroll
    {
        public static void main(String [] arg)
        {
        // Set up the formatters
        Date d = new Date();
        DateFormat df = DateFormat.getDateInstance();
        NumberFormat nf = NumberFormat.getCurrencyInstance();
    
        System.out.println("\nPayroll For Week Ending " + df.format(d));
        System.out.println("-------------------------------------");
        Payroll employee1 = new Payroll("444-4444", 30, 25);
        Payroll employee2 = new Payroll("555-5555", 20, 50);
        displaySalary(employee1, nf);
        displaySalary(employee2, nf);
    
        // Define employee 2
    
        System.out.println("\tIncrease " + employee1.getEmployeeId() + " by 10 hours");
        employee1.increaseHours(10); // 10 hours increase
        displaySalary(employee1, nf);
        // Re-calculate the salary and print
    
        System.out.println("Total payout amount.. " +  nf.format(Payroll.getTotalPayout()));
        System.out.println("------------ End of report ----------");
        }
        public static void displaySalary(Payroll e, NumberFormat nf)
        {
        System.out.println("\tEmployee # ........" + e.getEmployeeId());
        System.out.println("\tHours worked # ...." + e.getEmployeeHours());
        System.out.println("\tHourly rate # ....." + nf.format(e.getEmployeeRate()));
        System.out.println("\tYour salary is # .." + nf.format(e.calculateSalary()));
    
        // ….complete the method …..
        System.out.println("\t---------------------------------\n");
        }
    	}

  16. #16
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Quote Originally Posted by Fubarable View Post
    You've got a bug elsewhere in your program in code you're not showing us. I'm guessing you're setting hours to the salary somewhere, but without code, I can't tell.
    ... and I'm right:


    What do you think this method is going to do to hours? Should it be changing hours like it's doing?

    Java Code:
        public double calculateSalary()
        {
            return  hours *= rate;
        }

  17. #17
    ethemartian is offline Member
    Join Date
    Feb 2011
    Posts
    15
    Rep Power
    0

    Default

    Its calculating the salary of employee 1 and employee 2, heres what the output looks like:
    Java Code:
    Payroll For Week Ending Feb 5, 2011
    -------------------------------------
            Employee # ........444-4444
            Hours worked # ....30.0
            Hourly rate # .....$25.00
            Your salary is # ..$750.00
            ---------------------------------
    
            Employee # ........555-5555
            Hours worked # ....20.0
            Hourly rate # .....$50.00
            Your salary is # ..$1,000.00
            ---------------------------------
    
            Increase 444-4444 by 10 hours
            Employee # ........444-4444
            Hours worked # ....760.0
            Hourly rate # .....$25.00
            Your salary is # ..$19,000.00
            ---------------------------------
    
    Total payout amount.. $0.00
    ------------ End of report ----------
    Last edited by ethemartian; 02-05-2011 at 11:39 PM. Reason: Wrong output

  18. #18
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Quote Originally Posted by ethemartian View Post
    Its calculating the salary of employee 1 and employee 2, heres what the output looks like:
    It's doing more than that. In your return statement you're changing what hours is, and you shouldn't be doing that. You have

    Java Code:
    return  hours *= rate;
    What this does is multiply hours by rate and then set's hours to this value. The last part you don't want to do. So instead of hours *=, why not simply return rate * hour and don't put hours on the left side. Do you see why this matters?

  19. #19
    ethemartian is offline Member
    Join Date
    Feb 2011
    Posts
    15
    Rep Power
    0

    Default

    I havent got a clue why it changes it, have I mentioned my professor is not that good? So when you create a return statement it changes the variable on the left side?

  20. #20
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    When you say

    Java Code:
    return hours * rate;

    it means "multiple hours time rate and return that".


    When you say

    Java Code:
    return hours *= rate;

    it means "multiply hours times rate and assign that to hours and then return that value as well."

    (Changing hours would make the method a mutator, and we know it is supposed to be an accessor. It should change nothing - just get a calculate a value and return it.)

    -------------------------------

    I think what Fubarable was getting at is "don't put hours on the left side of an =" as that assignment is the very thing that changes a value.

Page 1 of 2 12 LastLast

Similar Threads

  1. Mutator method for a calculator
    By Krakatau7 in forum New To Java
    Replies: 15
    Last Post: 01-10-2011, 11:15 PM
  2. Calendar mutator problem
    By WimHaar in forum New To Java
    Replies: 7
    Last Post: 01-04-2011, 12:25 PM
  3. Accessor/Mutator Question
    By noble in forum New To Java
    Replies: 4
    Last Post: 02-02-2010, 04:21 AM
  4. Replies: 6
    Last Post: 12-02-2008, 11:15 PM
  5. mutator method
    By dirtycash in forum New To Java
    Replies: 7
    Last Post: 11-22-2007, 10:29 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •