Exam+prep+question+2+(short+answer)

(a) Write the code for an Employee class, which has the following fields: private String name; private double salary; Your class should contain the following:

(i) Provide a constructor to set the employee’s name using a passed argument and also to set the salary to $0.

(ii) Provide a constructor that accepts arguments to set the employee’s name and salary. The salary should be set using the mutator method for salary described below.

(iii) Provide a mutator (i.e. setter) method for the salary that ensures the salary remains within the inclusive range $0 to $100,000. If an attempt is made to set a salary outside this range the current salary will not be changed.

(iv) Provide accessor (i.e. getter) methods for the name and for the salary. (15 marks)

(b) Write a program, called TestEmployee.java, to do the following:

(i) Create an employee object referenced by emp1, using the name “Fred”.

(ii) Assign a salary of $45,000 for employee “Fred”.

(iii) Create an employee object referenced by emp2, using the name “Sue” and assigns her a salary of $55,000, all in the one statement.

(iv) On a separate line for each employee, display the employee’s name and 40% of the salary, for taxation purposes. (10 marks)

Ive tried doing this part. question is, how do i do the (marked) part of the question? can I use Array? Arraylist? Help! Laurens, if you read this, will you be able to check whether my coding is correct? thank you very much!

package pracexam; /**
 * @author User

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

Employee { }

purple comments by Laurens this is the constructor (i), it's OK Employee(String myName) { name = myName; salary = 0.0; }

//this is the other constructor (ii)// //Employee(String myName, double mySalary)// //{// //name = myName;// //salary = mySalary;// //}//

this is the setter (iii) "salary outside this range the current salary will not be changed." using System.exit is brutal, just do nothing, or, even better have some feedback ("error")

public void setSalary (double mySalary) { double myCounter = 0; myCounter = mySalary; if (myCounter < 0 || myCounter > 100000) { System.exit(0); } else { salary = myCounter; } }

//this is the accessor (iv)// //public String getName// //{// //return name;// //}//

this is the other // accessor // (v) public double getSalary { return salary; } }

=
=============================

public static void main(String[] args) { //TODO code application logic here// //Employee myEmployee = new Employee;// //Employee emp1 = new Employee("Fred");// //myEmployee.setSalary(45000);// //Employee emp2 = new Employee("Sue", 55000);// part b (i, ii, & iii above), there are some mistakes, try:

Employee emp1 = new Employee("Fred"); emp1.setSalary(45000); Employee emp2 = new Employee("Sue", 55000);

// part iv is just going to do some output using accessors, e.g. System.out.println(emp1.getName + emp1.getSalary * 0.4);