Inheritance - Creating a class Commission Employee from class Employee and testing - java

Good Morning, I've been given the assignment to:
rewrite the CommissionEmployee class as a subclass of Employee. CommissionEmployee should contain only the instance variables and methods that are not declared in superclass Employee. CommissionEmployee's constructor should invoke Employee's constructor and CommissionEmployee's toString method should invoke Employee's toString method.
Create a Driver class to test your new CommissionEmployee class. Prompt the user to input the first name, last name, social security number, gross sales, and commission rate and create a CommissionEmployee object, using the toString method to print its information.
The issue I seem to be having is class CommissionEmployeeTest will not output what I've placed in my toString method of class CommissionEmployee. I feel like like my superclass Employee is correct as well as me test class but my belief is the error lies somewhere in the method I've created to determine the earnings. The output I'm looking for is
Employees First Name Last Name
Social Security NUmber
Earnings
Earnings would be the total of gross sales + (commission rate * gross sales)
Here is what I have along with the error:
class Employee
public class Employee extends Object {
protected final String firstName;
protected final String lastName;
protected final String socialSecurityNumber;
public Employee(String firstName, String lastName, String socialSecurityNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.socialSecurityNumber = socialSecurityNumber;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getSocialSecurityNumber() {
return socialSecurityNumber;
}
#Override
public String toString() {
return String.format(firstName, lastName, socialSecurityNumber);
}
}
class CommissionEmployee
public class CommissionEmployee extends Employee {
private double grossSales;
private double commissionRate;
private double earnings;
public CommissionEmployee(String firstName, String lastName, String socialSecurityNumber, double grossSales,
double commissionRate, double earnings) {
super(firstName, lastName, socialSecurityNumber);
if (grossSales < 0.0)
throw new IllegalArgumentException("Gross sales must be >= 0.0");
if (commissionRate <= 0.0 || commissionRate >= 1.0)
throw new IllegalArgumentException("Commission rate must be > 0.0 and < 1.0");
this.grossSales = grossSales;
this.commissionRate = commissionRate;
}
public void setGrossSales(double grossSales) {
if (grossSales < 0.0)
throw new IllegalArgumentException("Gross sales must be >= 0.0");
this.grossSales = grossSales;
}
public double getGrossSales() {
return grossSales;
}
public void setCommissionRate(double commissionRate) {
if (commissionRate <= 0.0 || commissionRate >= 1.0)
throw new IllegalArgumentException("Commission rate must be > 0.0 and < 1.0");
this.commissionRate = commissionRate;
}
public double getCommissionRate() {
return commissionRate;
}
public Double earnings(double d) {
return earnings(grossSales+ (commissionRate * grossSales));
}
public double getEarnings() {
return earnings;
}
public void setEarnings(double earnings) {
this.earnings = earnings;
}
#Override
public String toString() {
return String.format("%s: %s %s%n%s: %s%n%s: %.2f%n%s: %.2f%n%s: %.2f%n%s",
"commission employee", firstName, lastName,
"social security number", socialSecurityNumber,
"Total earnings", earnings(earnings));
}
public void setFirstName(String firstName) {
}
public void setLastName(String lastName) {
}
public void setSocialSecurityNumber(String socialSecurityNumber) {
}
public void setGrossSales(String grossSales) {
}
public void setCommissionRate(String commissionRate) {
}
}
class CommissionEmployeeTest
//CommissionEmployee test program.
import java.util.Scanner;
public class CommissionEmployeeTest {
public static void main(String[] args) { // instantiate CommissionEmployee object
CommissionEmployee employee =
new CommissionEmployee(null, null, null, 0, .1, 0);
Scanner input = new Scanner(System.in);
// get commission employee data
System.out.printf(
"Employee information obtained by get methods:%n");
System.out.printf("Enter employee's First name:");
String firstName = input.nextLine();
employee.setFirstName(firstName);
System.out.printf("Enter employee's last name:");
String lastName = input.nextLine();
employee.setLastName(lastName);
System.out.printf("Enter employee's social security number:");
String socialSecurityNumber = input.nextLine();
employee.setSocialSecurityNumber(socialSecurityNumber);
System.out.printf("Gross sales for employee:");
String grossSales = input.nextLine();
employee.setGrossSales(grossSales);
System.out.printf("Commission rate for employee:");
String commissionRate = input.nextLine();
employee.setCommissionRate(commissionRate);
System.out.printf("%n%s:%n%n%s%n",
"Updated employee information obtained by toString",
employee.toString());
}
}
Error
Employee information obtained by get methods:
Enter employee's First name:John
Enter employee's last name:Doe
Enter employee's social security number:123456789
Gross sales for employee:4000.00
Commission rate for employee:.1
Exception in thread "main" java.lang.StackOverflowError
at CommissionEmployee.earnings(CommissionEmployee.java:45)
I've tried manipulating my toString method in CommissionEmployee as well as my method to determine earnings but I feel like I'm spinning my wheels. I appreciate any help. I have 1 week left in class and feel like I can contribute more information each week when I post a question then I did the last. Thank you in advance.

I have resolved the issue. After reviewing and revising(several times) I have found my answer. I needed revision on my toString method as well as my earnings method. Cleaned up quite a bit of the code and resolved.

Related

Using array to store and manipulate objects data with java

Im currently learning java and im trying to create an Employee management program that stores employee records into an array and allow management to manipulate the array and print any employee reports. So I create a menu and ten employee objects which got stored in an array...now what I want to do is allow the user to input employee details through the menu and that information will be stored inside the objects and I want the user to be able to search for an employee by their title and also display only male of female employees.
I first started with my employee class where has my modifers
public class Employee{
int emp_id=0;
String fname="pebbles";
String lname=null;
String dob=null;
String gender=null;
String address=null;
String title=null;
String dateHired=null;
String department=null;
int hoursWorked=0;
double rateOfpay=0.0;
int leaveDays=0;
double carAllowance=0.0;
double monthlyGratuity=0.0;
double taxRate=0.0;
public Employee(){}
public Employee(int emp_id,String fname,String lname,String dob,String gender,String address,String title,String dateHired,String
department,int hoursWorked,double rateOfpay,int leaveDays,double carAllowance,double monthlyGratuity,double taxRate){
this.emp_id=emp_id;
this.fname=fname;
this.lname=lname;
this.dob=dob;
this.gender=gender;
this.address=address;
this.title=title;
this.dateHired=dateHired;
this.department=department;
this.hoursWorked=hoursWorked;
this.rateOfpay=rateOfpay;
this.leaveDays=leaveDays;
this.carAllowance=carAllowance;
this.monthlyGratuity=monthlyGratuity;
this.taxRate=taxRate;
}
public Employee(int emp_id,String fname,String lname){
this.emp_id=emp_id;
this.fname=fname;
this.lname=lname;
}
public void setEmployeeId(int emp_id){
this.emp_id=emp_id;
}
public void setFirstName(String fname){
this.fname=fname;
}
public void setLastName(String lname){
this.lname=lname;
}
public void setDateOfBirth(String dob){
this.dob=dob;
}
public void setGender(String gender){
this.gender=gender;
}
public void setAddress(String address){
this.address=address;
}
public void setTitle(String title){
this.title=title;
}
public void setDateHired(String dateHired){
this.dateHired=dateHired;
}
public void setDepartment(String department){
this.department=department;
}
public void setHoursWorked(int hoursWorked){
this.hoursWorked=hoursWorked;
}
public void setRateOfPay(double rateOfpay){
this.rateOfpay=rateOfpay;
}
public void setLeaveDays(int leaveDays){
this.leaveDays=leaveDays;
}
public void setCarAllowance(double carAllowance){
this.carAllowance=carAllowance;
}
public void setMonthlyGratuity(double monthlyGratuity){
this.monthlyGratuity=monthlyGratuity;
}
public void setTaxRate(double taxRate){
this.taxRate=taxRate;
}
public int getEmployeeId(){
return emp_id;
}
public String getFirstName(){
return fname;
}
public String getLastName(){
return lname;
}
public String getDateOfBirth(){
return dob;
}
public String getGender(){
return gender;
}
public String getAddress(){
return address;
}
public String getTitle(){
return title;
}
public String getDateHired(){
return dateHired;
}
public String getDepartment(){
return department;
}
public int getHoursWorked(){
return hoursWorked;
}
public double getRateOfPay(){
return rateOfpay;
}
public int getLeaveDays(){
return leaveDays;
}
public double getCarAllowance(){
return carAllowance;
}
public double getMonthlyGratuity(){
return monthlyGratuity;
}
public double getTaxRate(){
return taxRate;
}
}
Then created the objects and arrays in the class below
import java.util.Scanner;
public class employeeArray extends Employee{
private static Employee employees[] = new Employee[10];
static Scanner input=null;
String fname="pebbles";
String lname=null;
String dob=null;
String gender=null;
int emp_id=0;
String address=null;
String title=null;
String dateHired=null;
String department=null;
int hoursWorked=0;
double rateOfpay=0.0;
int leaveDays=0;
double carAllowance=0.0;
double monthlyGratuity=0.0;
double taxRate=0.0;
public static Employee e1=new Employee(12345,"Aobakwe","Mothabi","26/07/1990","Male","Private 009 Masunga","CEO",
"06/02/2008","Finance",500,50.0,10,100.0,1500,5.1);
public static Employee e2=new Employee();
public static Employee e3=new Employee();
public static Employee e4=new Employee();
public static Employee e5=new Employee();
public static Employee e6=new Employee();
public static Employee e7=new Employee();
public static Employee e8=new Employee();
public static Employee e9=new Employee();
public static Employee e10=new Employee();
public static void main(String args[]){
input=new Scanner(System.in);
Employee e1=new Employee(12345," ","Mothabi","26/07/1990","Male","Private 009 Masunga","CEO",
"06/02/2008","Finance",500,50.0,10,100.0,1500,5.1);
Employee e2=new Employee();
Employee e3=new Employee();
Employee e4=new Employee();
Employee e5=new Employee();
Employee e6=new Employee();
Employee e7=new Employee();
Employee e8=new Employee();
Employee e9=new Employee();
Employee e10=new Employee();
employees[0]=e1;
employees[1]=e2;
employees[2]=e3;
employees[3]=e4;
employees[4]=e5;
employees[5]=e6;
employees[6]=e7;
employees[7]=e8;
employees[8]=e9;
employees[9]=e10;
//ENTER NAME
System.out.println("Enter name");
String fname=input.next();
e2.setFirstName(fname);
//ENTER LAST NAME
System.out.println("Enter surname");
String lname=input.next();
e2.setLastName(lname);
//ENTER DATE OF BIRTH
System.out.println("Enter date of birth");
String dob=input.next();
e2.setDateOfBirth(dob);
//ENTER GENDER
System.out.println("Enter Gender");
String gender=input.next();
e2.setGender(gender);
//ENTER EMPLOYEE ID
System.out.println("Enter Employee Id");
int emp_id=input.nextInt();
e2.setEmployeeId(emp_id);
//ENTER ADDRESS
System.out.println("Enter Address");
String address=input.next();
e2.setAddress(address);
//ENTER TITLE
System.out.println("Enter Employee Title");
String title=input.next();
e2.setTitle(title);
//ENTER DATE HIRED
System.out.println("Enter Date Hired");
String dateHired=input.next();
e2.setDateHired(dateHired);
//ENTER DEPARTMENT
System.out.println("Enter Department");
String department=input.next();
e2.setDepartment(department);
//ENTER HOURS WORKED
System.out.println("Enter Hours Worked");
int hoursWorked=input.nextInt();
e2.setHoursWorked(hoursWorked);
//ENTER RATE OF PAY
System.out.println("Enter Rate Of Pay");
double rateOfpay=input.nextDouble();
e2.setRateOfPay(rateOfpay);
//ENTER LEAVE DAYS
System.out.println("Enter Leave Days");
int leaveDays=input.nextInt();
e2.setLeaveDays(leaveDays);
//ENTER CAR ALLOWANCE
System.out.println("Enter Car Allowance");
double carAllowance=input.nextDouble();
e2.setCarAllowance(carAllowance);
//ENTER MONTHLY GRATUITY
System.out.println("Enter Monthly Gratuity");
double monthlyGratuity=input.nextDouble();
e2.setMonthlyGratuity(monthlyGratuity);
//ENTER TAX RATE
System.out.println("Enter Tax Rate");
double taxRate=input.nextDouble();
e2.setTaxRate(taxRate);
//DISPLAY RESULTS
System.out.println(e2.getFirstName());
System.out.println(e2.getLastName());
System.out.println(e2.getDateOfBirth());
System.out.println(e2.getGender());
System.out.println(e2.getEmployeeId());
System.out.println(e2.getAddress());
System.out.println(e2.getTitle());
System.out.println(e2.getDateHired());
System.out.println(e2.getDepartment());
System.out.println(e2.getHoursWorked());
System.out.println(e2.getRateOfPay());
System.out.println(e2.getLeaveDays());
System.out.println(e2.getCarAllowance());
System.out.println(e2.getMonthlyGratuity());
System.out.println(e2.getTaxRate());*/
}
static void mainMenu(){
System.out.println(
"Select an option\n"+
"1)Add Employee Records\n"+
"2) display only male of female employees\n"+
"3) display all employees and their gross salaries\n"+
"4) search for an employee and display salary calculated.\n");
}
}
and lastly here is my tester class which displays the menu and allows the user to select an option
import java.util.Scanner;
public class empTester extends employeeArray{
static Scanner input=null;
public static void main(String args[]){
input=new Scanner(System.in);
mainMenu();
int choice=input.nextInt();
if(choice==1){
menuAdd();
int option=input.nextInt();
if(option==1){EmployeeCreation();}
else if(option==2){System.out.println("It works number 2");}
else if(option==3){mainMenu();}
}
else if(choice==2){
menuDisplay();
int option=input.nextInt();
if(option==1){System.out.println("It works number 1");}
else if(option==2){System.out.println("It works number 2");}
else if(option==3){System.out.println("It works number 3");}
else if(option==4){System.out.println("It works number 4");}
else if(option==5){mainMenu();}
}
else if(choice==3){
menuSearch();
int option=input.nextInt();
if(option==1){System.out.println("It works number 1");}
else if(option==2){System.out.println("It works number 2");}
else if(option==3){mainMenu();}
}
else if(choice==4){
System.out.println("This is the About Section");
}
else if(choice==5){
System.out.println("Ending Program");
System.exit(0);
}
}
}
Yeah so I managed to find a way to enable the user to add an employee record and display details added. Im having trouble creating methods for other functions stated in the menu without having to create new objects.
I think you need a static list.
public static List<Employee> employees = new ArrayList<>();`
public void addEmployee() {
Employee employee = new Employee();
input=new Scanner(System.in);
String fname=input.next();
employee.setFirstName(fname);
.
.
. and others setters...
eployees.add(employee);
}
And read about toString() method to display object details.
toString(), ArrayList, static variable
Here are a few suggestions. The Employee class seems ok. Note that you do not need to supply default values for variables if they are the same as the type's default value. Ex:
String lname=null;
int hoursWorked=0;
double rateOfpay=0.0;
Is the same as
String lname;
int hoursWorked;
double rateOfpay;
You might consider adding a function to the class to read data from a Scanner:
class Employee {
....
boolean readFromIn(Scanner input)
{
//ENTER NAME
System.out.println("Enter name");
fname = input.next();
//ENTER LAST NAME
System.out.println("Enter surname");
lname = input.next();
etc....
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(lname);
....fill in rest
return sb.toString();
}
....
}
The entire employeeArray class seems necessary. But if you want that, there's no need for the temporary variables e1, e2, etc. You have the array, you can add directly to it. A loop helps here:
public class EmployeeArray /* extends Employee - does not extend Employee */
{
private static Employee employees[] = new Employee[10]; // why static?
public static void createEmployees()
{
Scanner in = new Scanner(System.in);
for (int i = 0; i < employees.length; i++) {
employees[i] = new Employee();
employees[i].readFromIn(in);
}
}
public static Employee getEmployee(int index)
{
if (index < 0 || index >= employees.length) {
throw new ArrayIndexOutOfBoundsException();
}
return employees[i];
}
}

To make the object variable private in another class

I have written the code this expected output:
Sample input :
Enter the passenger name:
Priya
Enter the gender(M or F / m or f):
F
Enter the age:
61
Enter the ticket no:
140
Enter the ticket price:
500.0
Sample Output 1 :
Ticket no:143
Passenger Name:Priya
Price of a ticket : 500.0
Total Amount : 375.0
I have to change the total amount value based on the age and gender for which I have written function.
My code:
Person.java
public class Person {
private String name;
private char gender;
private int age;
public void setName(String name ){
this.name = name;
}
public void setGender(char gender){
this.gender = gender ;
}
public void setAge(int age ){
this.age = age;
}
public String getName(){
return this.name;
}
public char getGender(){
return this.gender;
}
public int getAge(){
return this.age;
}
}
BusTicket.java
public class BusTicket {
private int ticketNo;
private float ticketPrice;
private float totalAmount;
Person person = new Person();
int age = person.getAge();
char g = person.getGender();
public void setTicketNo(int ticketNo){
this.ticketNo = ticketNo;
}
public void setTicketPrice(float ticketPrice){
this.ticketPrice = ticketPrice;
}
public void setTotalAmount(float totalAmount){
this.totalAmount = totalAmount;
}
public void calculateTotal()
{
if(age<16)
{
totalAmount = ticketPrice/2;
setTotalAmount(totalAmount);
}
else if(age>=60)
{
totalAmount = 3*(ticketPrice/4);
setTotalAmount(totalAmount);
}
else if(g == 'f'|| g== 'F')
{
totalAmount = 9*(ticketPrice/10);
setTotalAmount(totalAmount);
}
else{
setTotalAmount(ticketPrice);
}
}
public int getTicketNo(){
return this.ticketNo;
}
public float getTicketPrice(){
return this.ticketPrice;
}
public float getTotalAmount(){
return this.totalAmount;
}
}
TestMain.java
import java.util.Scanner;
public class TestMain {
public static BusTicket getTicketDetails()
{
Scanner sc = new Scanner(System.in);
BusTicket bt = new BusTicket();
System.out.println("Enter the ticket no:");
bt.setTicketNo(sc.nextInt());
System.out.println("Enter the ticket price:");
bt.setTicketPrice(sc.nextFloat());
return bt;
}
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
Person p = new Person();
BusTicket bt;
System.out.println("Enter the passenger name:");
p.setName(sc.nextLine());
System.out.println("Enter the gender(M or F/ m or f):");
p.setGender(sc.next().charAt(0));
System.out.println("Enter the age:");
p.setAge(sc.nextInt());
bt = getTicketDetails();
System.out.println("Ticket no:"+bt.getTicketNo());
System.out.println("Passenger Name:"+p.getName());
System.out.println("Price of a ticket : "+bt.getTicketPrice());
System.out.println("Total Amount : "+bt.getTotalAmount());
}
}
But my TotalAmount value is always coming 0.0, it is not getting updated.
And some test cases are failed please help to resolve them:
Fail 1 -
Incorrect access specifier/modifier for person -Should be a [private]
Fail 2 -
Check whether the signature(Returntype/Argument/AccessSpecifier/MethodName) of the method setPerson is correct
Fail 3-
Check whether the signature(Returntype/Argument/AccessSpecifier/MethodName) of the method getPerson is correct
Please Help
Thanks
You need to call calculateTotal to update totalAmount. Otherwise, it will be always 0.0.
...
System.out.println("Price of a ticket : "+bt.getTicketPrice());
bt.calculateTotal(); // Add this line
System.out.println("Total Amount : "+bt.getTotalAmount());
In your BusTicket class a new Person object is assigned to Person attribute and then you are trying to get age and gender details from that newly created Person object, but at this moment Person's age and gender are not populated yet.
Person person = new Person();
int age = person.getAge();
That's why you are getting 0. What should ideally happen is, you should pass the person object created using the input details to the BusTicket class and populate the BusTicket's person attribute with that person.For now I ll tell just that. :)
Give a try :)
In your BusTicket class, create a getter and setter for the Person object, and set the value from the main method.

Errors when trying to call a method

I have been looking around online, and I am still unsure of how to call a method in my child class. I am trying to call the pay() method in Executive, and when I type in the following code into my if statement, I keep getting an error.
staff[3].awardBonus(bonus);
I keep getting an error with this method. I'm not sure how to call that method... Thanks for any help!`import java.util.Scanner;
import java.util.Scanner;
public class Tester
{
public static void main (String args[])
{
Scanner scan = new Scanner(System.in);
StaffMember[] staff = new StaffMember[4];
String internName = "Susan 2";
String empName = "Tyler O.";
String hrName = "Becky R.";
String execName = "Daniel H.";
String address = "Brighton";
String phone = "420 - 0000";
String SSN = "12345789";
double rate = 1000;
staff [0] = new Intern(internName, address, phone);
staff [1] = new Employee(empName, address, phone, SSN, rate);
staff [2] = new HourlyEmployee(hrName, address, phone, SSN, rate);
staff [3] = new Executive(execName, address, phone, SSN, rate);
for (StaffMember staffPrint : staff)
{
System.out.println (staffPrint.toString() + "\n");
}
System.out.println("If you would like to give an executive a bonus, press 1. \nIf you would like to increase the hours of an hourly employee, press 2.");
int input = scan.nextInt();
if(input == 1)
{
double bonus = 0;
System.out.println("Enter the bonus for your employee: ");
bonus = scan.nextDouble();
}
}
Here is the Executive class, Employee class and the StaffMember class
public class Executive extends Employee
{
public Executive(String name, String address, String phone, String SSN, double rate)
{
super(name, address, phone, SSN, rate);
}
public double pay()
{
double money = super.pay();
return money;
}
public String toString()
{
String employee = super.toString();
return employee;
}
public void awardBonus(double execBonus)
{
rate += execBonus;
}
}
Employee
public class Employee extends StaffMember
{
String SSN;
double rate;
public Employee(String name, String address, String phone, String SSN, double rate)
{
super(name, address, phone);
this.SSN = SSN;
this.rate = rate;
}
public double pay()
{
return rate;
}
public String toString()
{
String employee = "";
employee = ("Name: " + name + "\nAddress: " + address + "\nPhone Number: " + phone + "\nSocial Security Number: " + SSN + "\nPay: " + pay());
return employee;
}
}
StaffMember
public abstract class StaffMember
{
String name;
String address;
String phone;
public StaffMember(String name, String address, String phone)
{
this.name = name;
this.address = address;
this.phone = phone;
}
public String toString()
{
String employee = "";
employee = ("Name: " + name + "\nAddress: " + address + "\nPhone Number: " + phone);
return employee;
}
public abstract double pay();
}
staff is a StaffMember array. When you reference any item from it (as you do it staff[3]), you get a StaffMember.
StaffMember does not have a method awardBonus().
Your problem is that you are trying to call an undefined method on your StaffMember object. In fact the method awardBonus() was not defined in your StaffMember class.
And in the code staff[3].awardBonus(bonus) you were trying to call awardBonus() on staff[3] which is a StaffMember instance.
By providing an awardBonus for all StaffMembers, you can call it on a StaffMember. For instance:
public abstract class StaffMember
{
public void awardBonus(double bonus) {
if (bonus > 0) {
throw new IllegalStateException("Only executives receive a bonus");
}
}
...
public class Executive extends StaffMember
{
#Override
public void awardBonus(double bonus) {
P.S. be careful to inform the company on this.
You can use:
// Check if staff[3] is really an Executive
if(staff[3] instanceof Executive) {
// Cast staff[3] to an Executive
Executive executive = ((Executive)staff[3]);
// Now you can call awardBonus
executive.awardBonus(bonus);
}
Because staff is an StaffMember-array which doesn't contains the methode awardBonus.
You know that staff[3] is an Executive, but your program doesn't. Therefore you have to check if staff[3] is an instanceof Executive so you can safely cast it to an Executive with Executive executive = (Executive)staff[3].

Formatting Issues with Java Code

I am having trouble formatting Strings as I keep getting MissingFormatArgumentException error:
Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier '%s'
at java.util.Formatter.format(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.lang.String.format(Unknown Source)
at Employee.toString(Employee.java:36)
at CommissionEmployee.toString(CommissionEmployee.java:112)
at CommissionEmployeeTest.main(CommissionEmployeeTest.java:20)
Here is my code
Employee Java SuperClass File
public class Employee {
private final String firstName;
private final String lastName;
private final String socialSecurityNumber;
//SuperClass Argument Constructor
public Employee(String firstName, String lastName, String socialSecurityNumber)
{
this.firstName = firstName;
this.lastName = lastName;
this.socialSecurityNumber = socialSecurityNumber;
}
//return first name
public String getFirstName()
{
return firstName;
}
//return last name
public String getLastName()
{
return lastName;
}
//get Social Security number
public String getSocialSecurityNumber(){
return socialSecurityNumber;
}
public String toString(){
return String.format("%s: %s %s%n%s: %s%n%s:", "commission employee",getFirstName(), getLastName(), "social security number", getSocialSecurityNumber());
}
}
Commission Employee SubClass
public class CommissionEmployee extends Employee {
//private final String firstName;
//private final String lastName;
//private final String socialSecurityNumber;
private double grossSales; //gross weekly sales
private double commissionRate; //commission percentage
//five argument constructor
public CommissionEmployee(String firstName, String lastName, String socialSecurityNumber, double grossSales, double commissionRate)
{
//implicit call to Object's default constructor occurs here
super(firstName,lastName,socialSecurityNumber);
//if grossSales is invalid throw exception
if(grossSales < 0.0 )
throw new IllegalArgumentException("Gross sales must be >=0.0");
//if commissionRate is invalid throw Exception
if(commissionRate<= 0.0 && commissionRate >= 1.0)
throw new IllegalArgumentException("Commission rate must be > 0.0 and < 1.0");
//this.firstName = firstName;
//this.lastName = lastName;
//this.socialSecurityNumber = socialSecurityNumber;
this.grossSales = grossSales;
this.commissionRate = commissionRate;
} //end constructor
//return first name
/*public String getFirstName()
{
return firstName;
}
//return last name
public String getLastName()
{
return lastName;
}
//get Social Security number
public String getSocialSecurityNumber(){
return socialSecurityNumber;
}
*/
//set gross Sales amount
public void setGrossSales(double grossSales)
{
if(grossSales <0.0)
throw new IllegalArgumentException("Gross sales must be >= 0.0");
this.grossSales = grossSales;
}
//return gross Sales amount
public double getGrossSales()
{
return grossSales;
}
//set commissionRate
public void setCommissionRate(double commissionRate)
{
if(commissionRate <=0.0 || commissionRate >=1.0)
throw new IllegalArgumentException("Commission rate must be >0.0 and <1.0");
this.commissionRate = commissionRate;
}
//return commissionRate
public double getCommissionRate()
{
return commissionRate;
}
//calculate Earnings
public double earnings()
{
return getCommissionRate() * getGrossSales();
}
//return String representation of CommissionEmployee object
//indicates that this method overrides a superclass method
public String toString()
{
return String.format("%s: %.2f%n%s: %.2f", "commission employee",super.toString(),"gross sales",getGrossSales(),"commission rate", getCommissionRate());
//return String.format("%s: %s %s%n%s: %s%n%s: %.2f%n%s: %.2f", "commission employee",getFirstName(), getLastName(), "social security number", getSocialSecurityNumber(),"gross sales",getGrossSales(),"commission rate", getCommissionRate());
}
}
Commission EmployeeTest Java
public class CommissionEmployeeTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
CommissionEmployee employee = new CommissionEmployee("Sam","randomlastname","123-34-5678",50.20,20.40);
//get commission employee data
System.out.println("Employee information obtained by get methods:");
System.out.printf("%n%s %s%n", "First name is",employee.getFirstName());
System.out.printf("%s %s%n", "Last name is", employee.getLastName());
System.out.printf("%s %s%n", "Social Security number is", employee.getSocialSecurityNumber());
System.out.printf("%s %.2f%n", "Gross Sales is", employee.getGrossSales());
System.out.printf("%s %.2f%n", "Commission Rate is", employee.getCommissionRate());
employee.setGrossSales(5000);
employee.setCommissionRate(0.1);
System.out.printf("%n%s:%n%n%s%n","Updated employee information obtained by toString",employee.toString());
}
}
Edit: Fixed my issues
Do you guys have any suggestions as to how I can fix my code?
In %s: %s %s%n%s: %s%n%s in Employee.toString(), I count six occurrences of %s, but only five arguments. I think you want to remove the very last %s.

Java compiler error: "cannot find symbol constructor .."?

i'm writing code for employee, manager, hourly worker for a class assignment but i've hit a problem that i can't figure out, the following is my code for employee followed by hourly worker. the problem is hourly worker won't compile, it's giving a "cannot find symbol constructor employee" error when i try to compile (employee class compiiles without issue. any suggestions please? i think i've been staring at it for so long i can no longer see the problem! thanks. pieter.
EMPLOYEE CLASS -
public class Employee
{
public String firstName;
public String lastName;
public double hourlyRate;
final static double NORMAL_WORKWEEK = 37.5;
public Employee(String firstName, String lastName, double hourlyRate)
{
setFirstName(firstName);
setLastName(lastName);
setHourlyRate(hourlyRate);
}
//Accessor and Mutator Methods for the employee's first name.
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
firstName = firstName;
}
//Accessor and Mutator Methods for the employee's last name.
public String getLastName()
{
return lastName;
}
public void setLastName(String lastName)
{
lastName = lastName;
}
//Access and Mutator Methods for the employee's hourly rate.
public double getHourlyRate()
{
return hourlyRate;
}
public void setHourlyRate(double hourlyRate)
{
//If the user input is valid, update the employee's hour rate with the newly input value.
if(hourlyRate > 0)
{
hourlyRate = hourlyRate;
}
//Otherwise prevent an hour rate greater than zero being overwritten
else if(hourlyRate <=0)
{
if(hourlyRate <= 0)
{
hourlyRate = 0;
}
decorateConsole();
//Alert the user to their mistake.
System.out.println("Error ! ! ! - An attempt to set the employee " + this.firstName + " " + this.lastName + "'s hourly rate to zero was detected.\n");
decorateConsole();
}
}
public void printState()
{
decorateConsole();
System.out.println("[FIRST NAME] = " + firstName + " [LAST NAME] = " + lastName + " [HOURLY RATE] = " + hourlyRate + "\n");
decorateConsole();
}
public void decorateConsole()
{
System.out.println("+-< EMPLOYEE INFO >-------------------------------------------------------------------------------------------------------------------------+\n");
}
HOURLY WORKER CLASS -
public class HourlyWorker extends Employee
{
private double wage;
private double hours;
public HourlyWorker(String firstName, String lastName, double hourlyWage, double hoursWorked)
{
super(firstName, lastName);
this.wage = wage;
this.hours = hours;
}
public void setWage (double hourlyWage)
{
this.wage = wage;
}
public void getWage()
{
return wage;
}
public void setHours (double hours)
{
this.hours = hours;
}
public double getHours()
{
return hours;
}
}
You don't have a Employee constructor with two parameters:
super(firstName, lastName);
Try using:
super(firstName, lastName, 0.0);
EDIT as per tony request, here's a more detailed explanation.
With super(firstName, lastName); you're invoking ( trying to invoke ) a constructor in the class Employee which has two string parameters.
Reviewing the Employee class definition, we see you don't have such constructor, but you have one with three parameters:
public Employee(String firstName, String lastName, double hourlyRate)
So, the solution is to invoke that constructor instead. Since you don't have a default value for hourlyRate we can use 0.0 which is a double.
Other alternative would be to create a two parameter constructor in the Employee class
public Employee(String firstName, String lastName )
In the HourlyWorker constructor you tried to call the Employee constructor like this:
super(firstName, lastName);
but the Employee class doesn't have a constructor with two parameters. You need to pass a third parameter (hourly rate) like this:
super(firstName, lastName, 42);
In HourlyWorker you call
super(firstName, lastName);
but the Employee constructor is
Employee(String, String, double)
The signatures don't match.
EDIT: Incidentally, why does the HourlyWorker have a private wage member? How is it different (conceptually) to Employee.hourlyRate?
In your HourlyWorker class you are calling the constructor of Employee {super(firstname, lastname)} with two arguments but in Employee class you do not have any constructors that take two arguments.
You don't have a super constructor that takes only two arguments.
HourlyWorker's constructor tries to call super(firstName, lastName), but there's no such constructor declared in the parent class.
In your HourlyWorker class, you have the following line of code:
super(firstName, lastName);
But, there is no matching constructor in your employee class. Basically, the compiler is looking in your employee class for something like...
public Employee(String firstName, String lastName)
{
...
}
Define a new constructor, or call the constructor you've defined with the parameters you're missing.
You are calling HourlyEmployee's base class constructor (which is Employee's ctor) with 2 arguments instead of the 3 it wants.
Change the line in HourlyEmployee ctor from:
super(firstName, lastName);
to
super(firstName, lastName, hourlyWage);
Also, if you are still wanting to have a constructor like
public Employee(String firstName, String lastName)
{
...
}
and you know the default value from your double hourlyRate, you can try to write a new constructor like the next one:
`public Employee(String firstName, String lastName)
{
Employee(firstName, lastName, 0.0);
}`
There's something fishy going on around the else if here. It's repeated with another if and some curly braces missing. Indent your code properly and make sure the open curlys matches the closing ones.
if(hourlyRate > 0)
{
hourlyRate = hourlyRate;
}
//Otherwise prevent an hour rate greater than zero being overwritten
else if(hourlyRate <=0)
{
if(hourlyRate <= 0)
{
hourlyRate = 0;
}
decorateConsole();
Also, these kind of lines won't work as intended (you have three of them):
firstName = firstName;
It must be:
this.firstName = firstName;
Like you have in your second class.

Categories