Making calculations in inheritance classe - java

I'm trying to make the program so that the dicountPrice would be equal to the corresponding if statement. I'm not too sure if it
s my if statement or if I'm missing something in my class. I've tried doing super.purchases and this.purchases and as of now I'm stumped.
Sample output:
Name: Snow White
Address: 111 Dwarf Lane
Telephone: 555-0000
Customer Number: 200-A010
Customer Type: Preferred
Total Purchases: 2566.0
Total Owed: 2566.0
Total Discount Percent: 0.0
Total Owed Minus Discount: 2566.0
But I need the discount percent to be 10
TIA
public class Customer extends Person {
protected String customerNumber, customerType;
protected double purchases;
Customer(){
super(DEFAULT_VALUE,DEFAULT_VALUE,DEFAULT_VALUE);
setCustomerType(DEFAULT_VALUE);
setPurchases(0.0);
}
Customer(String name, String address, String phone, String cusNum, String cusType, double purch){
super (name,address, phone);
customerNumber = cusNum;
customerType = cusType;
purchases = purch;
}
public void setCustomerNumber(String custNum){
customerNumber = custNum;
}
public String getCustomerNumber(){
return customerNumber;
}
public void setCustomerType(String cusType){
customerType = cusType;
}
public String getCustomerType(){
return customerType;
}
public void setPurchases(double purch){
purchases = purch;
}
public double getPurchases(){
return purchases;
}
public double getTotalOwed(){
return purchases;
}
public String toString(){
return super.toString() + "\nCustomer Number: " + customerNumber + "\nCustomer Type: " + customerType +
"\nTotal Purchases: " + purchases + "\nTotal Owed: " + purchases;
}
}
public class PreferredCustomer extends Customer {
private double discountPercent=0.0;
PreferredCustomer(){
super(DEFAULT_VALUE,DEFAULT_VALUE,DEFAULT_VALUE,DEFAULT_VALUE, DEFAULT_VALUE,0.0);
}
PreferredCustomer(String name, String address, String phone, String customerNumber, String customerType, double purchases){
super (name, address, phone, customerNumber, customerType, purchases);
}
public void setDiscountPercent(double dp){
discountPercent = dp;
}
public double getDiscountPercent(){
if (purchases >= 2000){
discountPercent = 100 * .10;
}
else if (purchases >= 1500 && purchases <2000){
discountPercent = 100 * .7;
}
else if (purchases >= 1000 && purchases <1500){
discountPercent = 100 * .6;
}
else if (purchases >=500 && purchases <1000){
discountPercent= 100 * .5;
}
else if(purchases<500){
discountPercent = 0;
}
return discountPercent ;
}
public double getTotalOwed(){
return purchases - discountPercent;
}
public String toString(){
return super.toString() + "\nTotal Discount Percent: " + discountPercent + "\nTotal Owed Minus Discount: " + this.getTotalOwed();
}
}

From what I see in your source, the issue comes from getDiscountPercent; You do calculations and modify members in a getter function which is a bad idea. A getter should only return data and not modify the internal state of the class.
A solution would be to create a private method called calculateDiscountPercent and call it internally whenever you modify members that would affect the discount percent value. Like this:
private void calculateDiscountPercent(){
if (purchases >= 2000){
discountPercent = 100 * .10;
}
else if (purchases >= 1500 && purchases <2000){
discountPercent = 100 * .7;
}
else if (purchases >= 1000 && purchases <1500){
discountPercent = 100 * .6;
}
else if (purchases >=500 && purchases <1000){
discountPercent= 100 * .5;
}
else if(purchases<500){
discountPercent = 0;
}
}
From the source, I see that the discountPercent is affected by the purchases member from its super class. Therefore, override its setter function to calculate the discount every time the purchase changes. Like so:
#Override
public void setPurchases(double purch){
super.setPurchases(purch);
this.calculateDiscountPercent();
}
Complete class would look like:
public class PreferredCustomer extends Customer {
private double discountPercent=0.0;
PreferredCustomer(){
super(DEFAULT_VALUE,DEFAULT_VALUE,DEFAULT_VALUE,DEFAULT_VALUE, DEFAULT_VALUE,0.0);
this.calculateDiscountPercent();
}
PreferredCustomer(String name, String address, String phone, String customerNumber, String customerType, double purchases){
super (name, address, phone, customerNumber, customerType, purchases);
this.calculateDiscountPercent();
}
public void setDiscountPercent(double dp){
discountPercent = dp;
}
public double getDiscountPercent(){
return discountPercent ;
}
#Override
public void setPurchases(double purch){
super.setPurchases(purch);
this.calculateDiscountPercent();
}
private void calculateDiscountPercent(){
if (purchases >= 2000){
discountPercent = 100 * .10;
}
else if (purchases >= 1500 && purchases <2000){
discountPercent = 100 * .7;
}
else if (purchases >= 1000 && purchases <1500){
discountPercent = 100 * .6;
}
else if (purchases >=500 && purchases <1000){
discountPercent= 100 * .5;
}
else if(purchases<500){
discountPercent = 0;
}
}
public double getTotalOwed(){
return purchases - discountPercent;
}
public String toString(){
return super.toString() + "\nTotal Discount Percent: " + discountPercent + "\nTotal Owed Minus Discount: " + this.getTotalOwed();
}
}

Related

Java - use void return type to allow customer to gain admission into event

I'm trying to make a method that allows a customer to gain admission into an event. As a requirement, the payAdmission() method should have a void return type. My method should also be one line long, making use of the computeFee() and spend() methods that are already written. I don't quite understand how I'm supposed to determine how a customer is supposed to pay admission when the return type is just void and I'm unable to subtract any values or return anything?
Code for Customer Class:
public class Customer {
String name;
int age;
float money;
public Customer(String initName){
name = initName;
}
public Customer(String initName, int initAge){
name = initName;
age = initAge;
}
public Customer(String initName, int initAge, float initMoney){
name = initName;
age = initAge;
money = initMoney;
}
public Customer(){
}
public float computeFee(){
if(age >= 18 && age <65){
return 12.75f;
}
if(age >= 65){
return 0.5f;
}
if(age >= 4 && age <= 17){
return 8.50f;
}
return 0.0f;
}
public boolean spend(float amount){
if(amount <= money){
money -= amount;
return true;
}else{
return false;
}
}
public boolean hasMoreMoneyThan(Customer c){
if(this.money > c.money){
return true;
}
return false;
}
public void payAdmission(){
float comF = computeFee();
float spe = spend();
float moneyLeft -= (comF + spe);
}
}
Code for CustomerAdmissionTestProgram:
public class CustomerAdmissionTestProgram {
public static void main(String args[]) {
Customer c1, c2, c3, c4;
c1 = new Customer("Bob", 17, 100);
c2 = new Customer("Dottie", 3, 10);
c3 = new Customer("Jane", 24, 40);
c4 = new Customer("Sam", 72, 5);
System.out.println("Here is the money before going into the circus:");
System.out.println(" Bob has $" + c1.money);
System.out.println(" Dottie has $" + c2.money);
System.out.println(" Jane has $" + c3.money);
System.out.println(" Sam has $" + c4.money);
// Simulate people going into the circus
c1.payAdmission();
c2.payAdmission();
c3.payAdmission();
c4.payAdmission();
System.out.println("Here is the money after going into the circus:");
System.out.println(" Bob has $" + c1.money);
System.out.println(" Dottie has $" + c2.money);
System.out.println(" Jane has $" + c3.money);
System.out.println(" Sam has $" + c4.money);
}
}
Look carefully at what the spend and computeFee methods do. spend takes in an amount and subtracts it from the money (if the person has enough money to spend, of course). The computeFee method calculates and returns the fee.
So what should payAdmission do? It naturally follows that it should spend the fee. How do you get the fee? By calling computeFee. How do you spend it? By calling spend.
So your method should be implemented like this:
spend(computeFee());
public static void main(String... args) {
List<Customer> customers = Arrays.asList(
new Customer("Bob", 17, 100),
new Customer("Dottie", 3, 10),
new Customer("Jane", 24, 40),
new Customer("Sam", 72, 5));
System.out.println("Here is the money before going into the circus:");
customers.forEach(customer -> System.out.format(" %s has $%.2f\n", customer.name, customer.money));
customers.forEach(Customer::payAdmission);
System.out.println("Here is the money after going into the circus:");
customers.forEach(customer -> System.out.format(" %s has $%.2f\n", customer.name, customer.money));
}
public static class Customer {
private final String name;
private final int age;
private double money;
public Customer(String name) {
this(name, 0);
}
public Customer(String name, int age) {
this(name, age, 0);
}
public Customer(String name, int age, double money) {
this.name = name;
this.age = Math.max(0, age);
this.money = Math.max(0, money);
}
public double computeFee() {
if (age >= 65)
return 0.5;
if (age >= 18)
return 12.75;
if (age >= 4)
return 8.50;
return 0;
}
public boolean spend(double amount) {
amount = Math.max(0, amount);
if (Double.compare(amount, money) > 0)
return false;
money -= amount;
return true;
}
public boolean hasMoreMoneyThan(Customer customer) {
return Double.compare(money, customer.money) > 0;
}
public void payAdmission() {
if (!spend(computeFee()))
throw new RuntimeException();
}
}

Not getting the right output

Probably just a small error, but I cant seem to find it anywhere. When I run the program, it prints "After depositing $100: Savings Account:, also my withdraw class seems not to be working, as the balance after withdrawing money does not change.
public class CheckingandSavings
{
public static void main(String[] args) {
Savings savings = new Savings(1001,1000.0);
Checking checking = new Checking(1002, 2000.0);
System.out.println("At the beginning: " + savings);
savings.deposit(100);
System.out.println("After depositing $100: " + savings);
savings.withdraw(500);
System.out.println("After withdrawing $500: " + savings);
System.out.println("");
System.out.println("At the beginning: " + checking);
checking.deposit(100);
System.out.println("After depositing $100: " + checking);
checking.withdraw(500);
System.out.println("After withdrawing $500: " + checking);
}
}
public class Account {
private int accountNumber;
private double accountBalance;
//The Two-Arg Constructor
public Account(int accountNumber, double accountBalance)
{
setAccountBalance(accountBalance);
setAccountNumber(accountNumber);
}
//Getter for accountNumber
public int getAccountNumber()
{
return accountNumber;
}
//Setter for accountNumber
public void setAccountNumber(int accountNumber)
{
if (accountNumber >= 0)
this.accountNumber = accountNumber;
}
//Getter for accountBalance
public double getAccountBalance()
{
return accountBalance;
}
//Setter for accountBalance
public void setAccountBalance(double accountBalance)
{
if (accountNumber >= 0)
this.accountBalance = accountBalance;
}
//Deposit to accountBalance
public void deposit(double amount)
{
if (amount > 0)
this.accountBalance += amount;
}
//Withdraw from accountBalance
public double withdraw(double amount)
{
if (amount > 0 || amount > this.accountBalance)
return 0;
this.accountBalance -= amount;
return this.;
}
//Returns a string of the instance data
public String toString()
{
String result = "";
result += "Account Number: " + this.accountNumber;
result += "\nAccount Balance: $" + String.format("%.2f", this.accountBalance);
return result;
}
}
public class Savings extends Account {
//The two-arg constructor
public Savings(int accountNumber, double accountBalance)
{
super(accountNumber, accountBalance);
}
//Returns a string of the instance data
public String toString()
{
String result = "";
result += "Savings Account: \n" + super.toString();
return result;
}
}
public class Checking extends Account {
//The two-arg constructor
public Checking(int accountNumber, double accountBalance)
{
super(accountNumber,accountBalance);
}
//Returns a string of the instance data
public String toString() {
String result = "";
result += "Checking Account: \n" + super.toString();
return result;
}
}
Taking a look at your withdraw method:
//Withdraw from accountBalance
public double withdraw(double amount)
{
if (amount > 0 || amount > this.accountBalance) //This needs to be &&
return 0;
this.accountBalance -= amount;
return this.; //I am assuming you meant this to be this.accountBalance?
}
You are saying if the amount you want to withdraw is greater than 0 OR it is greater than your account balance, return 0. I think you want to say AND so instead put amount > 0 && amount > this.accountBalance
Also, you should be returning this.accountBalance.
Lastly, you should really put the #Override annotation above your toString methods. This lets the compiler know you are overriding a parents method.

Java: How to get the return statement return all values

I tried write a table that displays the taxable income for an incremental taxable income from 50,0000 to 60,000 under 4 different filing categories. Employing a method, the return statement in the code only printed out one of the four filing categories columns. Please how can I get the remaining columns printed out?
public class TaxableIncome {
public static void main(String[] args) {
System.out.println("Taxable Income\t\t Single\t\t Married Joint\t\t MarriedSeerate\t\t HeadofaHouse");
System.out.println("-----------------------------------------------------------------------------------------------------");
double Tincome;
int profile=1;
for(Tincome=50000; Tincome<=60000; Tincome+=50) {
System.out.println( Tincome +"\t\t" + computetax(profile, Tincome));
}
}
public static double computetax( int status , double income) {
double tax;
double single=0;
double mjoint=0;
double mseperate=0;
double head=0;
for(status=1;status<=4;status++) {
if(status==1) {
tax = 8350*.10 + (33950-8350)*0.15 + (income- 33950)*0.25;
single= tax;
}
if(status==2) {
tax = 16700*0.10 + (income-16700)*0.15;
mjoint = tax;
}
if(status==3 ) {
tax = 8350*0.10 + (33950-8350)*0.15 + (income-33950)*0.25;
mseperate= tax;
}
if(status ==4){
tax = 11950*0.10 + (45500-11950)*0.15 +(income-45500)* 0.25;
head =tax;
}
}
return (single);
}
}
Or use System.out.print() to output each value as they're calculated within computeTax, then do a System.out.println(); to get a carriage return.
You should roll all of the calculation results into their own object and return one of those.
static class TaxDetails {
double single = 0;
double mjoint = 0;
double mseperate = 0;
double head = 0;
}
public static TaxDetails computetax(double income) {
TaxDetails details = new TaxDetails();
details.single = 8350 * .10 + (33950 - 8350) * 0.15 + (income - 33950) * 0.25;
details.mjoint = 16700 * 0.10 + (income - 16700) * 0.15;
details.mseperate = 8350 * 0.10 + (33950 - 8350) * 0.15 + (income - 33950) * 0.25;
details.head = 11950 * 0.10 + (45500 - 11950) * 0.15 + (income - 45500) * 0.25;
return details;
}
public void test() {
System.out.println("Taxable Income\t\t Single\t\t Married Joint\t\t MarriedSeerate\t\t HeadofaHouse");
System.out.println("-----------------------------------------------------------------------------------------------------");
for (double income = 50000; income <= 60000; income += 50) {
TaxDetails tax = computetax(income);
System.out.println(income + "\t\t" + tax.single + "\t\t" + tax.mjoint + "\t\t" + tax.mseperate + "\t\t" + tax.head);
}
}
You are calculating your value for tax four times, then discarding that and returning just the single value for single.
Move the loop on status out of computetax and into caller.
EDIT: given that you're on a self-study course, here's a version that should work within your constraints.
It still needs a lot of improvement, but will get you further.
public class TaxableIncome {
public static void main(String[] args) {
System.out.println("Taxable Income\t\t Single\t\t Married Joint\t\t MarriedSeerate\t\t HeadofaHouse");
System.out.println("-----------------------------------------------------------------------------------------------------");
double Tincome;
int profile=1;
for(Tincome=50000; Tincome<=60000; Tincome+=50) {
double single=computetax(1, Tincome);
double joint=computetax(2, Tincome);
double seperate=computetax(3, Tincome);
double head=computetax(4, Tincome);
System.out.println( Tincome +"\t\tsingle:\t" + single + "\tjoint:\t" + joint + "\tseparate:\t" + separate + "\thead:\t" + head);
}
}
public static double computetax( int status , double income) {
double tax;
double single=0;
double mjoint=0;
double mseperate=0;
double head=0;
if(status==1) {
tax = 8350*.10 + (33950-8350)*0.15 + (income- 33950)*0.25;
single= tax;
}
if(status==2) {
tax = 16700*0.10 + (income-16700)*0.15;
mjoint = tax;
}
if(status==3 ) {
tax = 8350*0.10 + (33950-8350)*0.15 + (income-33950)*0.25;
mseperate= tax;
}
if(status ==4){
tax = 11950*0.10 + (45500-11950)*0.15 +(income-45500)* 0.25;
head =tax;
}
}
return (single);
}
}

if statement logic not working

so i have these two classes called shipment and insurance, one calculates the price for shipping and the other adds the insurance. The shipment logic is working just fine but for some reason the if statements in Insurance class is not working i dont know whats going on. The output for the Insurance cost is always 2.45. why does it do this?
Shipment class:
package theshipment;
public class Shipment extends Main {
protected double weight = Double.parseDouble(savedArgs[1]);
protected double shippingCost;
protected double methodCost;
protected String method = savedArgs[2];
public void calculateShippingCost(){
if (weight<=10||weight>=1){
if (method.equalsIgnoreCase("T"))
methodCost = weight * 3.00;
else if (method.equalsIgnoreCase("A"))
methodCost = weight * 4.00;
else if (method.equalsIgnoreCase("M"))
methodCost = weight * 2.00;
else{}
}else if (weight<=20||weight>=10.1){
if (method.equalsIgnoreCase("T"))
methodCost = weight * 2.45;
else if (method.equalsIgnoreCase("A"))
methodCost = weight * 3.00;
else if (method.equalsIgnoreCase("M"))
methodCost = weight * 1.75;
else{}
}else if (weight>20){
if (method.equalsIgnoreCase("T"))
methodCost = weight * 1.95;
else if (method.equalsIgnoreCase("A"))
methodCost = weight * 2.50;
else if (method.equalsIgnoreCase("M"))
methodCost = weight * 1.55;
else{}
}else{}
}
}
And the insurance class:
package theshipment;
public class Insurance extends Shipment{
private void calculateInsurance(){
if (methodCost<=10.0||methodCost>=0.0)
shippingCost = methodCost + 2.45;
else if(methodCost<=30.0||methodCost>=10.1)
shippingCost = methodCost + 3.95;
else if(methodCost>=30.01)
shippingCost = methodCost + 5.55;
else{}
}
public void run(){
calculateShippingCost();
calculateInsurance();
}
public String displayOrder(){
return ("Method cost: " + methodCost + " " + "Insurance cost: " +
(shippingCost-methodCost) + " Total shipping cost: " + shippingCost);
}
}
methodCost<=10.0||methodCost>=0.0 that means it will be true when methodCost will be bigger than 0 OR smaller than 10,
I believe you want range not all numbers change it to methodCost<=10.0 && methodCost>=0.0

Polymorphism and instanceof

I have programed a Worker and MachineWorker class. It complies fine. but when i run it, after three consecutive statements the program stops. I cannot find the problem, and I dont know how and when to use 'instanceof'.
I am writing the question below and with all the classes...
Question:- (i)Declare an array that can store the references of up to 5 Worker or MachineWorker objects.
a)Allow user to enter the type of object and the data for that type of object(3 values for Worker and 4 values for MachineWorker).
b)Construct the appropriate object storing the reference in the common array.
ii)Now allow the users to enter the weekly data repeatedly. If it is Worker object user must enter ID and hours-worked. If it is a MachineWorker object user must enter ID,hoursWorked and pieces. Once these values read search through the array to locate the object with the given ID before calling the addWeekly().The number of arguments either(1 or 2) to be passed to addWeekly depends on the type of objects being referred. To determine the type of object being referred(Worker or MachineWorker)you may use the instanceof operator.
Please see my codes below:-
//Worker.java
public class Worker {
public final double bonus=100;
protected String name, workerID;
protected double hourlyRate, totalHoursWorked,tax,grossSalary,netSalary;
public Worker(){
}
public Worker(String name, String workerID, double hourlyRate){
this.name = name;
this.workerID = workerID;
this.hourlyRate = hourlyRate;
}
public void addWeekly(double hoursWorked){
this.totalHoursWorked = this.totalHoursWorked + hoursWorked;
}
public double gross(){
grossSalary = (totalHoursWorked*hourlyRate);
if(totalHoursWorked>=150){
grossSalary = grossSalary +100;
}
return grossSalary;
}
public double netAndTax(){
netSalary = grossSalary;
if(grossSalary>500){
tax = (grossSalary - 500) *0.3;
netSalary = (grossSalary - tax);
}
return netSalary;
}
public String getName(){
return this.name;
}
public String getWorkerID(){
return this.workerID;
}
public double getHourlyRate(){
return this.hourlyRate;
}
public double getTotalHours(){
return totalHoursWorked;
}
public double getGrossSalary(){
return grossSalary;
}
public void addToGross(double amt){
grossSalary = grossSalary + amt;
}
public void displaySalary(){
System.out.print("Name: " +getName() + "\nID :" + getWorkerID()
+ "\nHourly Rate: " + getHourlyRate()+ "\nTotalHours Worked" + getTotalHours() +
"\nGross pay" + getGrossSalary() + "\nTax: " + netAndTax() +
"\nNet Pay: " + netAndTax());
}
}
//MachineWorker.java
public class MachineWorker extends Worker{
private double targetAmount;
private double totalPieces, productivityBonus;
public MachineWorker(String workerName, String workerID, double hourlyRate, double targetAmount)
{
super(workerName, workerID, hourlyRate);
//this.productivityBonus = productivityBonus;
this.targetAmount = targetAmount;
}
public void addWeekly(double hoursWorked, double weeklyAmount)
{
totalHoursWorked = hoursWorked + totalHoursWorked;
totalPieces = weeklyAmount + totalPieces;
}
public double productivityBonus()
{
productivityBonus = 100 + (totalPieces - targetAmount);
return productivityBonus;
}
public double gross()
{
grossSalary = (totalHoursWorked * hourlyRate) + productivityBonus;
if(totalHoursWorked >= 150)
{
grossSalary = grossSalary + bonus;
}
return grossSalary;
}
public void addToGross(double amt)
{
amt = productivityBonus;
grossSalary = grossSalary + amt;
}
public void displaySalary()
{
System.out.println("Name " + super.name + "\nID " +
super.workerID + "\nHourly rate " + super.hourlyRate + "\nTotal Hours Worked " +
super.totalHoursWorked + "\nGross Pay $" + super.grossSalary + "\nTax $" + super.tax + "\nNetpay $" + super.netSalary);
System.out.println("Productivity Bonus " + productivityBonus);
}
}
//Polymorphism PolyWorker.java
import java.util.*;
public class PolyWorkers
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
Worker[] a = new Worker[5];
MachineWorker[] b = new MachineWorker[5];
char option = '0';
String choice;
boolean nChar = false;
for (int i = 0; i < 5; i++){
System.out.print("\tType of object " + (i+1) + " [W/M]: ");
choice = input.nextLine();
if (choice.length() == 1)
{
option = choice.charAt(0); //pick the first character
if (option == 'w' || option == 'W')
{
System.out.println("\n\tEnter name, ID and hours: ");
String name = input.nextLine();
System.out.print(" ");
String id = input.nextLine();
System.out.print(" ");
double hours = input.nextDouble();
a[i] = new Worker(name, id, hours);
System.out.println();
}
if (option == 'm' || option == 'M')
{
System.out.print("\n\tEnter name, ID, hours and pieces: ");
String name = input.nextLine();
System.out.print(" ");
String id = input.nextLine();
System.out.print(" ");
double hours = input.nextDouble();
System.out.print(" ");
double pieces = input.nextDouble();
b[i] = new MachineWorker(name, id, hours, pieces);
System.out.println();
}
System.out.print("\tType of object " + (i+1) + " [W/M]: ");
choice = input.nextLine();
}
a[i].displaySalary();
b[i].displaySalary();
b[i].productivityBonus();
}
}
}
You might want to use overriden methods readfromInput and displaySalary to distinguish between what Worker and Machinworker does.
The different behaviour should be implemented within the classes and not in the calling Polyworker class.
If Machineworker displaySalary shows the bonus this should be called in displaySalary of MachineWorker
see modified code below
//Worker.java
import java.util.Scanner;
/**
* a generic worker
*/
public class Worker {
public final double bonus = 100;
protected String name, workerID;
protected double hourlyRate, totalHoursWorked, tax, grossSalary, netSalary;
public void addWeekly(double hoursWorked) {
this.totalHoursWorked = this.totalHoursWorked + hoursWorked;
}
public double gross() {
grossSalary = (totalHoursWorked * hourlyRate);
if (totalHoursWorked >= 150) {
grossSalary = grossSalary + 100;
}
return grossSalary;
}
public double netAndTax() {
netSalary = grossSalary;
if (grossSalary > 500) {
tax = (grossSalary - 500) * 0.3;
netSalary = (grossSalary - tax);
}
return netSalary;
}
public String getName() {
return this.name;
}
public String getWorkerID() {
return this.workerID;
}
public double getHourlyRate() {
return this.hourlyRate;
}
public double getTotalHours() {
return totalHoursWorked;
}
public double getGrossSalary() {
return grossSalary;
}
public void addToGross(double amt) {
grossSalary = grossSalary + amt;
}
public void displaySalary() {
System.out.print("Name: " + getName() + "\nID :" + getWorkerID()
+ "\nHourly Rate: " + getHourlyRate() + "\nTotalHours Worked"
+ getTotalHours() + "\nGross pay" + getGrossSalary() + "\nTax: "
+ netAndTax() + "\nNet Pay: " + netAndTax());
}
public void readFromInput(Scanner input) {
name = input.nextLine();
System.out.print(" ");
this.workerID= input.nextLine();
System.out.print(" ");
this.totalHoursWorked = input.nextDouble();
System.out.println();
}
} // Worker
//MachineWorker.java
import java.util.Scanner;
public class MachineWorker extends Worker {
private double targetAmount;
private double totalPieces, productivityBonus;
public void addWeekly(double hoursWorked, double weeklyAmount) {
totalHoursWorked = hoursWorked + totalHoursWorked;
totalPieces = weeklyAmount + totalPieces;
}
public double productivityBonus() {
productivityBonus = 100 + (totalPieces - targetAmount);
return productivityBonus;
}
public double gross() {
grossSalary = (totalHoursWorked * hourlyRate) + productivityBonus;
if (totalHoursWorked >= 150) {
grossSalary = grossSalary + bonus;
}
return grossSalary;
}
public void addToGross(double amt) {
amt = productivityBonus;
grossSalary = grossSalary + amt;
}
#Override
public void displaySalary() {
super.displaySalary();
System.out.println("Productivity Bonus " + productivityBonus);
}
#Override
public void readFromInput(Scanner input) {
super.readFromInput(input);
this.totalPieces = input.nextDouble();
}
}
//Polymorphism PolyWorker.java
import java.util.*;
public class PolyWorkers {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
Worker[] workers = new Worker[5];
char option = '0';
String choice;
for (int i = 0; i < 5; i++) {
System.out.print("\tType of object " + (i + 1) + " [W/M]: ");
choice = input.nextLine();
if (choice.length() == 1) {
option = choice.toLowerCase().charAt(0); // pick the first character
switch (option) {
case 'w': {
workers[i] = new Worker();
System.out.println("\n\tEnter name, ID and hours: ");
}
break;
case 'm': {
System.out.print("\n\tEnter name, ID, hours and pieces: ");
}
break;
} // switch
workers[i].readFromInput(input);
}
workers[i].displaySalary();
}
}
}
Your question states that you have to store the references in a common array, where as you are storing them in 2 different arrays a and b. As you have different arrays for different type of objects, you don't have the need to use instanceOf operator. More about instanceOf is here.
Also, you do not check for null while printing salary or bonus. As at any point of the loop, only one type of object will be created, one of a[i] or b[i] will be definitely null, causing a NullPointerException.
You need another loop after the one you have already written that will allow the user to input the worker's hours. This will presumably be a while loop that will continually ask for input. You would then choose some sort of input that would quit the loop. Inside the loop you ask for hours and take either 2 or 3 arguments.
At the moment you are not storing your Workers/MachineWorkers. You need to create an array to store them in. You also need to create either a base class or an interface that they will both extend/implement. This will allow you to create a single array to store them all.
You then loop through your array of Workers/MachineWorkers and when you find a matching id you use your instanceof to work out whether you need to pass 1 or 2 arguments. If it is a MachineWorker you should cast it as such and then call the appropriate method with 2 arguments.

Categories

Resources