My programming assignment tasked me with writing an increase/decreasePay abstract method that must be put in my abstract employee class. I can't seem to get the the method correct in HourlyWorker so that it will take increase or decrease the pay by a "percentage". My math is sound (monthly pay - or + (monthly pay * the percentage), but my output in my test class is coming out the same after increasing/decreasing pay. Any help?
Employee class:
abstract public class Employee
{
private String lastName;
private String firstName;
private String ID;
public abstract void increasePay(double percentage);
public abstract void decreasePay(double percentage);
public abstract double getMonthlyPay();
public Employee(String last, String first, String ID)
{
lastName = last;
firstName = first;
this.ID = ID;
}
public void setLast(String last)
{
lastName = last;
}
public void setFirst(String first)
{
firstName = first;
}
public void setIdNumber(String ID)
{
this.ID = ID;
}
public String getLastName()
{
return lastName;
}
public String getFirstName()
{
return firstName;
}
public String getName()
{
return firstName + lastName;
}
public String getIdNumber()
{
return ID;
}
}
HourlyWorkerClass
public class HourlyWorker extends Employee
{
private int hours;
private double hourlyRate;
private double monthlyPay;
public HourlyWorker(String last, String first, String ID, double rate)
{
super(last, first, ID);
hourlyRate = rate;
}
public void setHours(int hours)
{
this.hours = hours;
}
public int getHours()
{
return hours;
}
public void setHourlyRate(double rate)
{
if ( hours > 160 )
this.hourlyRate = hourlyRate * 1.5;
else
this.hourlyRate = rate;
}
public double getHourlyRate()
{
return hourlyRate;
}
public void setMonthlyPay(double monthlyPay)
{
monthlyPay = hourlyRate * hours;
}
public double getMonthlyPay()
{
return hourlyRate * hours;
}
public void increasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
public void decreasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
public String toString()
{
String result = "Name: " + getFirstName() + " " + getLastName() + "\nID: "
+ getIdNumber() + " \nHourly Rate: " + hourlyRate;
return result;
}
}
Testing class (currently testing increase
public class TestEmployee2
{
public static void main(String[] args)
{
Employee [] staff = new Employee[3];
Supervisor sup = new Supervisor("Boss", "Jim", "JB7865", 54000);
HourlyWorker hw1 = new HourlyWorker("Bee", "Busy", "BB1265", 11.95);
hw1.setHours(200);
staff[0] = sup;
staff[1] = hw1;
System.out.println(staff[0].getMonthlyPay());
staff[0].increasePay(5);
System.out.println(staff[0].getMonthlyPay());
System.out.println(staff[1].getMonthlyPay());
staff[1].increasePay(10);
System.out.println(staff[1].getMonthlyPay());
}
}
Supervisor class:
public class Supervisor extends Employee
{
private double annualSalary;
private double monthlyPay;
public Supervisor(String last, String first, String ID, double salary)
{
super(last, first, ID);
annualSalary = salary;
}
public void setAnnualSalary(double salary)
{
annualSalary = salary;
}
public double getAnnualSalary()
{
return annualSalary;
}
public double getMonthlyPay()
{
return ((annualSalary + (annualSalary * .02)) / 12);
}
public void increasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
public void decreasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
public String toString()
{
String result = "Name: " + getFirstName() + " " + getLastName() + "\nID: "
+ getIdNumber() + "\nAnnual Salary: " + annualSalary;
return result;
}
}
Output is:
4590.0
4590.0
2390.0
2390.0
Doesn't appear to be modifying getMonthlyPay()
Should be:
4590.00
4819.50
2390.00
2629.00
In increasePay, you are increasing monthlyPay:
public void increasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
But when you getMonthlyPay, you calculate the pay using two other variables - hourlyRate and hours:
public double getMonthlyPay()
{
return hourlyRate * hours;
}
So changing monthlyPay doesn't affect what getMonthlyPay returns. I suspect a similar thing happens in Supervisor.
increasePay should instead increase hourlyRate:
public void increasePay(double percentage)
{
hourlyRate *= 1 + percentage / 100;
}
Also, I don't think you need a monthlyPay field (or setMonthlyPay, for that matter) in HourlyEmployee at all. The monthly rate can always be calculated by hours and hourlyRate.
For Supervisor, do the same thing, and change annualSalary rather than monthlyPay:
public double getMonthlyPay()
{
return ((annualSalary + (annualSalary * .02)) / 12);
}
public void increasePay(double percentage)
{
annualSalary *= 1 + percentage / 100;
}
Related
/* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication3;
class Employee {
private String name;
private String address;
private int number;
public Employee(Employee emp) {
System.out.println("Constructing an Employee");
this.name = emp.name;
this.address = emp.address;
this.number = emp.number;
}
/*public Employee(String name, String address, int number) {
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}*/
public void mailCheck() {
System.out.println("Mailing a check to " + this.name
+ " " + this.address);
}
public String toString() {
return name + " " + address + " " + number;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public void setAddress(String newAddress) {
address = newAddress;
}
public int getNumber() {
return number;
}
}
class Salary extends Employee {
private double salary; //Annual salary
public Salary(Salary obj) {
super(obj);
setSalary(obj.salary);
}
/*public Salary(String name, String address, int number, double Salary) {
super(name, address, number);
setSalary(Salary);
}*/
public void mailCheck() {
System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing check to " + getName()
+ " with salary " + salary);
}
public double getSalary() {
return salary;
}
public void setSalary(double newSalary) {
if (newSalary >= 0.0) {
salary = newSalary;
}
}
public double computePay() {
System.out.println("Computing salary pay for " + getName());
return salary / 52;
}
}
public class JavaApplication3 {
public static void main(String[] args) {
Salary s = new Salary("Mohd Mohtashim", "Ambehta,UP", 3, 2000.00); // error why
System.out.println("Call mailCheck using Salary reference --");
s.mailCheck();
}
}
If we removed the comments from the constructor, then it will be okay. Why?
Salary s = new Salary("Mohd Mohtashim", "Ambehta,UP", 3, 2000.00); you're calling a constructor that takes multiple parameters but it doesn't exist since you've commented it out .
I am trying to verify what is wrong with my class builds to make address class communicate with my warehouse class. My get() and set methods along with toString() is in question. Any help would be greatly appreciated
public class Address
{
private String street;
private String city;
private String state;
private int zip;
public Address()
{
setStreet("");
setCity("");
setState("");
setZip(0);
}
public Address(String str, String c, String sta, int z)
{
setStreet(str);
setCity(c);
setState(sta);
setZip(z);
}
public String getStreet()
(
return street;
}
public String getCity()
{
return city;
}
public String getState()
{
return state;
}
public int getZip()
{
return zip;
}
public void setStreet( String str)
{
street = str;
}
public void setCity( String c)
{
city = c;
}
public void setState( String sta )
{
state = sta;
}
public void setZip( String z )
{
zip = z;
}
public String toString()
{
return( " Street " + street + " City " + city +" State " + state + " Zip " + zip);
}
}
Must communicate with the following warehouse class:
public class Warehouse
{
private double squareFeetSize;
private double pricePerSquareFoot;
private int televisions;
private int computers;
private Address address;
public Warehouse()
{
setSquareFeetSize(0.0);
setPricePerSquareFoot(0.0);
setTelevisions(0);
setComputers(0);
setAddress(new Address());
}
public Warehouse( double s, double p, int t, int c, Address a)
{
setSquareFeetSize(s);
setPricePerSquareFoot(p);
setTelevisions(t);
setComputers(c);
setAddress(a);
}
public double getSquareFeetSize()
{
return squareFeetSize;
}
public double getPricePerSquareFoot()
{
return pricePerSquareFoot;
}
public int getTelevisions()
{
return televisions;
}
public int getComputers()
{
return computers;
}
public Address getAddress()
{
return address;
}
public void setSquareFeetSize( double s)
{
squareFeetSize = s;
}
public void setPricePerSquareFoot ( double p )
{
pricePerSquareFoot = p;
}
public void setTelevisions ( int t )
{
televisions = t;
}
public void setComputers ( int c)
{
computers = c;
}
public void setAddress( Address a)
{
address = a;
}
public String toString()
{
return (" Square Foot Size " + squareFeetSize + " Price Per Square Foot " +
pricePerSquareFoot + " Televisions " + televisions + " Computers " +
computers + " Address " + address.toString());
}
public double calculateWarehouseCharge()
{
double charge = 0.0;
charge = (squareFeetSize * pricePerSquareFoot + (2.25 * televisions) + (5.50 * computers));
return charge;
}
public double purchaseTelevision( int quantity, double price)
{
double cost = 0.0;
if( quantity > televisions)
{
JOptionPane.showMessageDialog(null, "Television Quantity Unavailable");
price = 0.0;
}
else
{
cost = price * quantity;
televisions = televisions - quantity;
}
return cost;
}
public double purchaseComputer( int quantity, double price)
{
double cost = 0.0;
if( quantity > computers)
{
JOptionPane.showMessageDialog(null, "Computer Quantity Unavailable");
price = 0.0;
}
else
{
cost = price * quantity;
computers = computers - quantity;
}
return cost;
}
}
class Address{
private street = "123 Lame Street";
public getStreet(){
return street;
}
}
class Warehouse{
Address address = new Address(); // create an instance; not just declare
public void shipping(){
shipTo(address.getStreet()); // Here's how to "communicate"
}
}
You are on correct way. Your code is working. Because ToString is method of Object class that you overwrite in your class. http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html
Are you not getting correct result ?
I keep getting a nullPointerException and the rest of my code won't run. I have two classes setup. One is the SalesPerson and the other contains the main method. Line 42 is marked and that is where the nullPointerException occurs.
This is line 42
System.out.printf("%-20s %15.2f %14.2f %n", list[i].getFirstName() + " " + list[i].getLastName(), list[i].getTotalSales(), list[i].getSalary());
public class SalesPerson {
private String firstName;
private String lastName;
private double firstSales;
private double secondSales;
private double thirdSales;
private double fourthSales;
private double totalSales;
private double salary;
public SalesPerson(String lastName, String firstName, double firstSales,
double secondSales, double thirdSales, double fourthSales,
double totalSales, double salary) {
this.lastName = lastName;
this.firstName = firstName;
this.firstSales = firstSales;
this.secondSales = secondSales;
this.thirdSales = thirdSales;
this.fourthSales = fourthSales;
this.totalSales = totalSales;
this.salary = salary;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public double getTotalSales() {
return totalSales;
}
public void setTotalSales(double totalSales) {
this.totalSales = totalSales;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public double getFirstSales() {
return firstSales;
}
public void setFirstSales(double firstSales) {
if (firstSales >= 0) {
this.firstSales = firstSales;
} else {
System.out.println("First sales must be greater than zero.");
}
}
public double getSecondSales() {
return secondSales;
}
public void setSecondSales(double secondSales) {
if (secondSales >= 0) {
this.secondSales = secondSales;
} else {
System.out.println("Second sales must be greater than zero.");
}
}
public double getThirdSales() {
return thirdSales;
}
public void setThirdSales(double thirdSales) {
if (thirdSales >= 0) {
this.thirdSales = thirdSales;
} else {
System.out.println("Third sales must be greater than zero.");
}
}
public double getFourthSales() {
return fourthSales;
}
public void setFourthSales(double fourthSales) {
if (fourthSales >= 0) {
this.fourthSales = fourthSales;
} else {
System.out.println("Fourth sales must be greater than zero.");
}
}
}
SECOND CLASS
import java.io.File;
import java.util.Scanner;
public class Assignment10 {
public static final int NUM_SALESPEOPLE = 20;
public static final double NUM_PER_SALARY = 25;
public static void main(String[] args) {
SalesPerson[] list = new SalesPerson[NUM_SALESPEOPLE];
try {
int people = 0;
Scanner fileInput = new Scanner(new File("A10.txt"));
while (fileInput.hasNext()) {
String lastName = fileInput.next();
String firstName = fileInput.next();
double firstSales = fileInput.nextDouble();
double secondSales = fileInput.nextDouble();
double thirdSales = fileInput.nextDouble();
double fourthSales = fileInput.nextDouble();
double totalSales = firstSales + secondSales + thirdSales + fourthSales;
double salary = NUM_PER_SALARY * totalSales;
SalesPerson person = new SalesPerson(lastName, firstName,
firstSales, secondSales, thirdSales, fourthSales, totalSales, salary);
list[people] = person;
people++;
}
} catch (Exception ex) {
System.out.println("Error opening file.");
}
System.out.println("Full Name Total Sales Salary");
System.out.println("========= =========== ======");
for (int i = 0; i < NUM_SALESPEOPLE; i++) {
System.out.printf("%-20s %15.2f %14.2f %n", list[i].getFirstName() + " " + list[i].getLastName(), list[i].getTotalSales(), list[i].getSalary());
}
System.out.println("===================================================");
}
}
You are creating an array of size 20. This array will hold only references to NULL. If in your file you have less than 20 entries you will end up with a nullpointerexception.
To be sure, try to print the value of people. If it less than 20 then this is normal.
Your file 'A10.txt' doesn't have 20 (correct) lines.
You should not create an Array. Use ArrayList and Iterator instead and you won't have such problems.
Simply add a check for null:
for (int i = 0; i < NUM_SALESPEOPLE; i++) {
if (list[i] != null) {
System.out.printf("%-20s %15.2f %14.2f %n", list[i].getFirstName() + " " + list[i].getLastName(), list[i].getTotalSales(), list[i].getSalary());
}
}
or declare
int people = 0;
two lines earlier (before your try-block) and use this number of actual read people as the upper bound in your for loop instead of NUM_SALESPEOPLE.
Hi everyone I am trying to implement the strategy pattern but I can not set the amount in the concrete classes, what i mean is that the amount is remianing the same as the one in the helper class that has a relationship with the interface. I tried with to set the value with the constructor and the setter and getter methods but it is not working if you can have a look and give some feedback it would be graet.Here is the code.
public interface InvoicingAlgorithm
{
public void getInvoice(String name, double amount);
}
public class AmericanInvoice implements InvoicingAlgorithm
{
AmericanInvoice()
{
}
//Uk: america 1 : 1.57
#Override
public void getInvoice(String name, double amount)
{
Customer customer = new Customer(name , amount * 1.57);
customer.setAmount(amount * 1.57);
customer.getInvoice();
}
}
public class Customer
{
/**
* #param name represent the name of the Customer
*/
private String name;
/**
* #param amount represent the amount of money
*/
private double amount;
/**
* #param i represents object of InvoicingAlgorithm
*/
private InvoicingAlgorithm i;
Customer(String name, double amount)
{
this.name = name;
this.amount = amount;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public InvoicingAlgorithm getI() {
return i;
}
public void setInvoicingAlgorithm(InvoicingAlgorithm i)
{
this.i = i;
}
public String getInvoice()
{
DecimalFormat df = new DecimalFormat("#.00");
String total = "--------------------------------------TO: "
+ name + "FROM: Easyflap (UK) AMOUNT" + ":$" +
df.format(amount)
+ "--------------------------------------";
return total;
}
}
So when I test it it is returning the value --------------------------------------TO: OracleFROM: Easyflap (UK) AMOUNT:$500.00-------------------------------------- which is from the method getInvoice in the Customer class when I try to modify the amount in AmericanInvoice it is not working.
The test class for the AmericanInvoice
public class AmericanInvoiceTest {
/**
* Test of getInvoice method, of class AmericanInvoice.
*/
#Test
public void testGetInvoice() {
System.out.println("Producing American invoice");
final int invoiceAmount = 500;
final Customer c = new Customer("Oracle", invoiceAmount);
c.setInvoicingAlgorithm(new AmericanInvoice());
String actualOutput = c.getInvoice();
final File f = new File("actual-american.txt");
FileUtility.resetFile(f);
FileUtility.writeFile(f, actualOutput);
String expectedOutput = FileUtility.readFile(new File("expected-american.txt"));
//System.out.println(actualOutput);
//System.out.println(expectedOutput);
actualOutput = actualOutput.replaceAll("\\s", "");
expectedOutput = expectedOutput.replaceAll("\\s", "");
//System.out.println(actualOutput);
//System.out.println(expectedOutput);
assertEquals(actualOutput, expectedOutput);
}
}
You don't actually call any methods on the strategy object itself!
I don't condone using the strategy pattern this way as current exchange rates does not require using the Strategy Pattern. But the following code is most likely what you intended to do based on your example.
public interface InvoicingAlgorithm {
public double adjustInvoice(double amount);
}
public class AmericanInvoice implements InvoicingAlgorithm {
//Uk: america 1 : 1.57
#Override
public double adjustInvoice(double amount) {
return amount * 1.57;
}
}
public class Customer {
/**
* #param name represent the name of the Customer
*/
private String name;
/**
* #param amount represent the amount of money
*/
private double amount;
/**
* #param i represents object of InvoicingAlgorithm
*/
private InvoicingAlgorithm i;
Customer(String name, double amount) {
this.name = name;
this.amount = amount;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public InvoicingAlgorithm getI() {
return i;
}
public void setInvoicingAlgorithm(InvoicingAlgorithm i) {
this.i = i;
}
public String getInvoice() {
DecimalFormat df = new DecimalFormat("#.00");
String total = "--------------------------------------TO: "
+ name + "FROM: Easyflap (UK) AMOUNT" + ":$" +
df.format(i.adjustInvoice(amount))
+ "--------------------------------------";
return total;
}
}
I'm having some trouble with a hw assignment. In one assignment, we had to create a Person class. Mine was:
public class Person
{
String firstName;
String lastName;
String telephone;
String email;
public Person()
{
firstName = "";
lastName = "";
telephone = "";
email = "";
}
public Person(String firstName)
{
this.firstName = firstName;
}
public Person(String firstName, String lastName, String telephone, String email)
{
this.firstName = firstName;
this.lastName = lastName;
this.telephone = telephone;
this.email = email;
}
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public String getTelephone()
{
return telephone;
}
public void setTelephone(String telephone)
{
this.telephone = telephone;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public boolean equals(Object otherObject)
{
// a quick test to see if the objects are identical
if (this == otherObject) {
return true;
}
// must return false if the explicit parameter is null
if (otherObject == null) {
return false;
}
if (!(otherObject instanceof Person)) {
return false;
}
Person other = (Person) otherObject;
return firstName.equals(other.firstName) && lastName.equals(other.lastName) &&
telephone.equals(other.telephone) && email.equals(other.email);
}
public int hashCode()
{
return 7 * firstName.hashCode() +
11 * lastName.hashCode() +
13 * telephone.hashCode() +
15 * email.hashCode();
}
public String toString()
{
return getClass().getName() + "[firstName = " + firstName + '\n'
+ "lastName = " + lastName + '\n'
+ "telephone = " + telephone + '\n'
+ "email = " + email + "]";
}
}
Now we have to create a Loan class that uses Person as an attribute, and then extend that Loan class. My Loan class is:
public abstract class Loan
{
public void setLoanId(int nextId)
{
loanId = nextId;
nextId++;
}
public int getLoanId()
{
return loanId;
}
public void setInterestRate(double interestRate)
{
this.interestRate = interestRate;
}
public double getInterestRate()
{
return interestRate;
}
public void setLoanLength(int loanLength)
{
this.loanLength = loanLength;
}
public int getLoanLength()
{
return loanLength;
}
public void setLoanAmount(double loanAmount)
{
this.loanAmount = loanAmount;
}
public double getLoanAmount(double loanAmount)
{
return loanAmount;
}
public void printPayments()
{
double monthlyInterest;
double monthlyPrincipalPaid;
double newPrincipal;
int paymentNumber = 1;
double monthlyInterestRate = interestRate / 1200;
double monthlyPayment = loanAmount * (monthlyInterestRate) /
(1 - Math.pow((1 + monthlyInterestRate),( -1 * loanLength)));
// amortization table
while (loanAmount != 0) {
monthlyInterest = loanAmount * monthlyInterestRate;
monthlyPrincipalPaid = monthlyPayment - monthlyInterest;
newPrincipal = loanAmount - monthlyPrincipalPaid;
loanAmount = newPrincipal;
System.out.println("Payment Number | Interest | Principal | Loan Balance");
System.out.printf("%d, %.2f, %f, %f", paymentNumber++, monthlyInterest, newPrincipal, loanAmount);
}
}
/*
//method to print first payment
public double getFirstPayment()
{
}
method to print last payment
public double getLastPayment()
{
}*/
private Person client;
private int loanId;
private double interestRate;
private int loanLength;
private double loanAmount;
private static int nextId = 1;
}
And then extended the Loan class with CarLoan class, there is a function prototype of:
public CarLoan(Person client, double vehiclePrice, double downPayment, double salesTax,
double interestRate, CAR_LOAN_TERMS length)
I'm confused on how I use the Person constructor from the superclass. I cannot necessarily do
super(client);
in my constructor which is what the book did with some primitive types in their example. Not sure what the correct thing to do is... Any thoughts? Thanks!
CarLoan should not extend Person. That makes no sense since a CarLoan can't be a Person.
But Person can be a class variable in the CarLoan class.
public class CarLoan {
private Person client;
private double vehiclePrice;
public CarLoan(Person client, double vehiclePrice, double downPayment, double salesTax, double interestRate, CAR_LOAN_TERMS length) {
this.client = client;
this.vehiclePrice = vehiclePrice;
..
}
}
It looks like you want to be using composition in stead of inheritance.
In plain english, a CarLoan has a client (of type Person). A CarLoan itself is not a Person (which inheritance would suggest).
So you should do what Espen suggests (composition), in stead of CarLoan extends Person (inheritance).
A possibly legit use of inheritance would be:
class Waiter extends Person {
String employeeId;
// A waiter is a person with some extra information
public Waiter(String firstName, String lastName, String telephone,
String email, String employeeId) {
super(firstName, lastName, telephone, email); // must be first
this.employeeId = employeeId;
}
}
If CarLoan is to extend Person, then Person becomes the superclass of CarLoan.
From within the constructor of CarLoan you must always call one of the Person constructors via the super keyword before any other processing takes place.
However, it seems to me very much like you must be confused, as your prototype method passes an instance of Person to CarLoan. Further, I cannot see why a class called CarLoan would extend a person.