Not getting the right output - java

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.

Related

Checking account - Problem with withdrawing with overdraft

I'm having trouble with a Java OOP exercise. The program uses two classes, the object class Account and the Main class to print whatever the user wants.
It's a standard checkings account with an overdraft limit, the issue I'm having is printing out the account balance if the user decides to withdraw more than the account balance, I can't seem to get the overdraft logic down, can anyone help me out?
Account classs
public boolean withdraw(double amount) {
balance = this.getBalance() + overDraftLimit;
if ((balance - amount) >= 0) {
this.setBalance(this.getBalance() - amount);
balance -= amount;
return true;
} else if ((balance - amount) <= 0) {
System.out.println("The amount you wish to withdraw is more than your balance -> Using overdraft to complete your transaction!");
this.setBalance((this.getBalance() - amount) + overDraftLimit);
return true;
}
return false;
} // ***** WITHDRAW *****
// ***** toString *****
#Override
public String toString() {
return "Account numer: " + accountNumber + "\nYour current balance is: $" + balance + "\nYour overdraft limit is: $" + overDraftLimit;
}
}
### Main class
Account ac1 = new Account();
ac1.setAccountNumber(1234);
ac1.setOverDraftLimit(50);
System.out.println(ac1);
System.out.println("\nSucessful deposit");
ac1.deposit(100);
System.out.println("Your current balance is: $" + ac1.getBalance());
makeWithdraw(ac1, 50);
makeWithdraw(ac1, 50);
makeWithdraw(ac1, 25);
}
public static void makeWithdraw (Account ac1, double amount) {
if (ac1.withdraw(amount)) {
System.out.println("Withdraw was sucessful! Your new balance is: $" + ac1.getBalance());
} else {
System.out.println("Insufficient funds! Cannot withdraw " + amount + "Your current balance is: $" + ac1.getBalance());
}
}
}
This is the output:
This will be the proper logic to handle the overdraft during withdrawl.
public boolean withdraw(double amount) {
if(balance < -overDraftLimit) {
return false;
}
if ((balance - amount) >= -overDraftLimit) {
this.setBalance(this.getBalance() - amount);
balance -= amount;
return true;
}
return false;
} // ***** WITHDRAW *****
[EDIT]
Here is an running example
public class Test{
public static class A {
private int balance = 20;
private int overDraftLimit = 50;
public boolean withdraw(double amount) {
if(balance < -overDraftLimit) {
return false;
}
if ((balance - amount) >= -overDraftLimit) {
balance -= amount;
return true;
}
return false;
}
public int getBalance() {
return balance;
}
}
public static void main(String []args){
A a = new A();
System.out.println(a.getBalance());
System.out.println(a.withdraw(30));
System.out.println(a.getBalance());
System.out.println(a.withdraw(40));
System.out.println(a.getBalance());
System.out.println(a.withdraw(1));
System.out.println(a.getBalance());
}
}
Output:
20
true
-10
true
-50
false
-50

Making calculations in inheritance classe

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();
}
}

Array List Average

I'm trying to figure out how to get the Max & Min accounts to also print prints its account number, balance and average transaction amount.
I've tried all sorts of garb and have gotten nowhere.
import java.util.ArrayList;
import java.util.Scanner;
public class BankAccount {
private int AccountNumber;
public int getAccountNumber()
{
return AccountNumber;
}
private double Balance;
public double getBalance()
{
return Balance;
}
private ArrayList<Double> transactions = new ArrayList<Double>();
public void Deposit(double Balance)
{
transactions.add(Balance);
this.Balance = this.Balance + Balance;
}
public void Withdraw(double Balance)
{
transactions.add(-Balance);
this.Balance = this.Balance - Balance;
}
public BankAccount(int initialAccountNumber, double initialBalance)
{
this.Balance = initialBalance;
this.AccountNumber = initialAccountNumber;
transactions.add(initialBalance);
}
public double getAverage()
{
double sum = 0;
for (double element : transactions)
{
sum = sum + Math.abs(element);
}
double Average = sum / transactions.size();
return Average;
}
}
---
import java.util.ArrayList;
public class Bank {
private ArrayList<BankAccount> accounts = new ArrayList<BankAccount>();
public void MakeAccount(int initialAccountNumber, double initialBalance)
{
BankAccount NewAcc = new BankAccount(initialAccountNumber, initialBalance);
accounts.add(NewAcc);
}
public BankAccount FindLarAcc(int initialAccountNumber, double initialBalance)
{
BankAccount largest = accounts.get(0);
for (int i = 1; i < accounts.size(); i++)
{
BankAccount a = accounts.get(i);
if (a.getBalance() > largest.getBalance())
largest = a;
}
return largest;
}
public BankAccount FindLowAcc(int initialAccountNumber, double initialBalance)
{
BankAccount smallest = accounts.get(0);
for (int i = 1; i < accounts.size(); i++)
{
BankAccount a = accounts.get(i);
if (a.getBalance() < smallest.getBalance())
smallest = a;
}
return smallest;
}
public BankAccount FindAcc(int initialAccountNumber)
{
for (BankAccount a: accounts)
{
if (a.getAccountNumber() == initialAccountNumber)
return a;
}
return null;
}
}
---
import java.util.Scanner;
public class BankTester {
public static void main(String[] args){
Scanner in = new Scanner (System.in);
/**int AccountNumber = 0;*/
double Balance = 0;
double Amount = 0;
Bank Bank1 = new Bank();
boolean done = false;
while (!done)
{
System.out.println("Enter an Account Number to begin, enter -1 to quit: ");
int AccountNumber = in.nextInt();
if (AccountNumber == -1)
{
done = true;
} else {
System.out.println("Now enter a Balance: ");
Balance = in.nextDouble();
Bank1.MakeAccount(AccountNumber, Balance);
BankAccount B = Bank1.FindAcc(AccountNumber);
System.out.println("How much would you like to deposit? ");
Amount = in.nextDouble();
B.Deposit(Amount);
System.out.println("How much would you like to withdrawl? ");
Amount = in.nextDouble();
B.Withdraw(Amount);
}
BankAccount Max = Bank1.FindLarAcc(AccountNumber, Balance);
BankAccount Min = Bank1.FindLowAcc(AccountNumber, Balance);
/**
* Print & Compute Average
*/
System.out.println("Account " + Min.getAccountNumber() +
" has the smallest balance. ");
System.out.println("Account " + Max.getAccountNumber() +
" has the largest balance. ");
}
}
}
For those who might have had the same problem...I figured it out!
This belongs on the BankTester class, btw
System.out.println("Account " + Min.getAccountNumber() +
" has the smallest balance of, " + Min.getBalance() +
" and a average transaction of, " + Min.getAverage());
System.out.println("Account " + Max.getAccountNumber() +
" has the largest balance of, " + Max.getBalance() +
" and a average transaction of, " + Max.getAverage());

Calling Methods (Java)

Summary, I am to write a class called BankAccount and my professor has provided me with a driver.
Here is my class so far:
import java.util.Date;
public class BankAccount implements AccountInterface
{
private double balance;
private String name;
private Date creationDate = new Date ();
private boolean frozen;
private double limit;
private final double MAXLIMIT = 500;
private int accountNumber;
private static int howMany;
public BankAccount( )
{
this.name = "Classified";
this.creationDate.getTime();
this.frozen = false;
this.limit = 300;
this.howMany++;
this.accountNumber = howMany;
this.balance = 0;
}
public BankAccount (String creationName)
{
this.name = creationName;
this.creationDate.getTime();
this.frozen = false;
this.limit = 300;
this.howMany++;
this.accountNumber = howMany;
this.balance = 0;
}
public static int getNumAccounts ( )
{
return howMany;
}
public void deposit(double theMoney)
{
if (frozen = true)
throw new IllegalStateException ("Cannot Deposit - Account Is Frozen");
else if (theMoney < 0)
throw new IllegalArgumentException("Insufficient funds");
else
balance = balance + theMoney;
}
public double withdraw(double theMoney)
{
if (theMoney < 0 || balance == 0 || theMoney > limit || theMoney % 20 !=0)
throw new IllegalArgumentException ("There was an error in your withdraw.");
else if (frozen = true)
throw new IllegalStateException ("Cannot Deposit - Account Is Frozen");
else
balance = balance - theMoney;
return balance;
}
public double getBalance()
{
return balance;
}
public void freeze()
{
frozen = true;
}
public void unfreeze()
{
frozen = false;
}
public void setLimit(double newLimit)
{
if (newLimit < 0 || newLimit > MAXLIMIT)
throw new IllegalArgumentException ("There was a limit error.");
else if (frozen = true)
throw new IllegalStateException ("Cannot Deposit - Account Is Frozen");
else
limit = newLimit;
}
public double getLimit( )
{
return limit;
}
public String toString( )
{
return "\nAccount number: " + accountNumber + "\nName: " + name + "\nCreation Date: " + creationDate + "\nBalance: " + balance + "\nWithdrawal Limit: " + limit ;
}
}
The problem that I am running into is when the driver calls myAccount.unfreeze(); in my class it does not set the account to unfreeze. So When the driver goes to deposit any money my class returns Cannot Deposit - Account Is Frozen even though I have a method called unfreeze. I thought at first I might have missed spelled frozen or unfreeze wrong, but that is not the case. Hopefully, some fresh pair of eyes can spot something that I am skipping over.
Thank you for your help!
When you use single equation sign, you are assigning the value. Use double equal sign to check for equality. In your case you should be using if(frozen==false) and if(frozen==true) whenever you are checking for its value.

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