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.
Related
In my code, I was able to use the scanner feature to prompt the user to type a piece of text, however, I was only able to make it so the user can type once. To type again I would have to close the terminal, and open it again, how can I make it so that I can just type infinitely so that I wouldn't have to close it and reopen it every time in order to type again?
For context, this is my code, it is about a ticket machine which displays certain data, like the name of the person, the price, the total balance, etc. Currently I am doing the places. This means that I want the user to type any city in England, and a price would appear. But as I said, the user can only jarringly type one thing at a time, when they should be able to type without any limit.
import java.util.Scanner;
import java.lang.String;
public class TicketMachine
{
private int price;
private int balance;
private int total;
/**
* Create a machine that issues tickets of the given price.
*/
public TicketMachine(int cost)
{
price = cost;
balance = 0;
total = 0;
}
/**
* #Return The price of a ticket.
*/
public int getPrice()
{
return price;
}
/**
* Return The amount of money already inserted for the
* next ticket.
*/
public int getBalance()
{
return balance;
}
/**
* Receive an amount of money from a customer.
* Check that the amount is sensible.
*/
public void insertMoney(int amount)
{
if(amount > 0) {
balance = balance + amount;
}
else {
System.out.println("Use a positive amount rather than: " +
amount);
}
}
/**
* Print a ticket if enough money has been inserted, and
* reduce the current balance by the ticket price. Print
* an error message if more money is required.
*/
public void printTicket()
{
if(balance >= price) {
// Simulate the printing of a ticket.
System.out.println("HERE IS YOUR TICKET");
System.out.println("# Ticket");
System.out.println("# " + price + " cents.");
System.out.println("You have" + balance + "left");
// Update the total collected with the price.
total = total + price;
// Reduce the balance by the price.
balance = balance - price;
}
else {
System.out.println("You must insert at least: " +
(price - balance) + " more cents.");
}
}
/**
* Return the money in the balance.
* The balance is cleared.
*/
public int refundBalance()
{
int amountToRefund;
amountToRefund = balance;
balance = 0;
return amountToRefund;
}
public static void main(String [] args)
{
Scanner myScanner = new Scanner(System.in);
String answer = myScanner.nextLine();
if( answer.equals("London") )
{
System.out.println("£15");
}
if( answer.equals("Manchester") )
{
System.out.println("£20");
}
if( answer.equals("Brighton") )
{
System.out.println("£25");
}
if( answer.equals("Cornwall") )
{
System.out.println("£30");
}
if( answer.equals("Crystal Palace") )
{
System.out.println("£35");
}
if( answer.equals("Chealsea") )
{
System.out.println("£40");
}
if( answer.equals("Birmingham") )
{
System.out.println("£45");
}
if( answer.equals("Liverpool") )
{
System.out.println("£50");
}
if( answer.equals("Bristol") )
{
System.out.println("£55");
}
if( answer.equals("Leister") )
{
System.out.println("£60");
}
if( answer.equals("Newcastle") )
{
System.out.println("£65");
}
if( answer.equals("Cambridge") )
{
System.out.println("£70");
}
if( answer.equals("Bradford") )
{
System.out.println("£75");
}
if( answer.equals("Leeds") )
{
System.out.println("£80");
}
if( answer.equals("Oxford") )
{
System.out.println("£85");
}
if( answer.equals("Nottingham") )
{
System.out.println("£90");
}
if( answer.equals("Peterborough") )
{
System.out.println("£95");
}
if( answer.equals("Sheffield") )
{
System.out.println("£100");
}
}
}
Using a while true or a infinite loop isn't a good practice. You can use a do-while and check a flag (e.g. "exit") to close the program e.g.
import java.util.Scanner;
import java.lang.String;
public class TicketMachine {
private int price;
private int balance;
private int total;
/**
* Create a machine that issues tickets of the given price.
*/
public TicketMachine(int cost) {
price = cost;
balance = 0;
total = 0;
}
/**
* #Return The price of a ticket.
*/
public int getPrice() {
return price;
}
/**
* Return The amount of money already inserted for the next ticket.
*/
public int getBalance() {
return balance;
}
/**
* Receive an amount of money from a customer. Check that the amount is sensible.
*/
public void insertMoney(int amount) {
if (amount > 0) {
balance = balance + amount;
} else {
System.out.println("Use a positive amount rather than: "
+ amount);
}
}
/**
* Print a ticket if enough money has been inserted, and reduce the current balance by the
* ticket price. Print an error message if more money is required.
*/
public void printTicket() {
if (balance >= price) {
// Simulate the printing of a ticket.
System.out.println("HERE IS YOUR TICKET");
System.out.println("# Ticket");
System.out.println("# " + price + " cents.");
System.out.println("You have" + balance + "left");
// Update the total collected with the price.
total = total + price;
// Reduce the balance by the price.
balance = balance - price;
} else {
System.out.println("You must insert at least: "
+ (price - balance) + " more cents.");
}
}
/**
* Return the money in the balance. The balance is cleared.
*/
public int refundBalance() {
int amountToRefund;
amountToRefund = balance;
balance = 0;
return amountToRefund;
}
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
String answer = "";
do {
System.out.println("Enter your city, please:");
answer = myScanner.nextLine();
if (answer.equals("London")) {
System.out.println("£15");
}
else if (answer.equals("Manchester")) {
System.out.println("£20");
}
else if (answer.equals("Brighton")) {
System.out.println("£25");
}
else if (answer.equals("Cornwall")) {
System.out.println("£30");
}
else if (answer.equals("Crystal Palace")) {
System.out.println("£35");
}
else if (answer.equals("Chealsea")) {
System.out.println("£40");
}
else if (answer.equals("Birmingham")) {
System.out.println("£45");
}
else if (answer.equals("Liverpool")) {
System.out.println("£50");
}
else if (answer.equals("Bristol")) {
System.out.println("£55");
}
else if (answer.equals("Leister")) {
System.out.println("£60");
}
else if (answer.equals("Newcastle")) {
System.out.println("£65");
}
else if (answer.equals("Cambridge")) {
System.out.println("£70");
}
else if (answer.equals("Bradford")) {
System.out.println("£75");
}
else if (answer.equals("Leeds")) {
System.out.println("£80");
}
else if (answer.equals("Oxford")) {
System.out.println("£85");
}
else if (answer.equals("Nottingham")) {
System.out.println("£90");
}
else if (answer.equals("Peterborough")) {
System.out.println("£95");
}
else if (answer.equals("Sheffield")) {
System.out.println("£100");
}else {
System.out.println("ERROR: INVALID INPUT");
}
} while (answer != "exit");
}
}
PS use a switch case instead of if(){} e.g
import java.util.Scanner;
import java.lang.String;
public class TicketMachine {
private int price;
private int balance;
private int total;
/**
* Create a machine that issues tickets of the given price.
*/
public TicketMachine(int cost) {
price = cost;
balance = 0;
total = 0;
}
/**
* #Return The price of a ticket.
*/
public int getPrice() {
return price;
}
/**
* Return The amount of money already inserted for the next ticket.
*/
public int getBalance() {
return balance;
}
/**
* Receive an amount of money from a customer. Check that the amount is sensible.
*/
public void insertMoney(int amount) {
if (amount > 0) {
balance = balance + amount;
} else {
System.out.println("Use a positive amount rather than: "
+ amount);
}
}
/**
* Print a ticket if enough money has been inserted, and reduce the current balance by the
* ticket price. Print an error message if more money is required.
*/
public void printTicket() {
if (balance >= price) {
// Simulate the printing of a ticket.
System.out.println("HERE IS YOUR TICKET");
System.out.println("# Ticket");
System.out.println("# " + price + " cents.");
System.out.println("You have" + balance + "left");
// Update the total collected with the price.
total = total + price;
// Reduce the balance by the price.
balance = balance - price;
} else {
System.out.println("You must insert at least: "
+ (price - balance) + " more cents.");
}
}
/**
* Return the money in the balance. The balance is cleared.
*/
public int refundBalance() {
int amountToRefund;
amountToRefund = balance;
balance = 0;
return amountToRefund;
}
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
String answer = "";
do {
System.out.println("Enter your city, please:");
answer = myScanner.nextLine();
switch (answer) {
case "London":
System.out.println("£15");
break;
case "Manchester":
System.out.println("£20");
break;
case "Brighton":
System.out.println("£25");
break;
case "Cornwall":
System.out.println("£30");
break;
case "Crystal Palace":
System.out.println("£35");
break;
case "Chealsea":
System.out.println("£40");
break;
case "Birmingham":
System.out.println("£45");
break;
case "Liverpool":
System.out.println("£50");
break;
case "Bristol":
System.out.println("£55");
break;
case "Leister":
System.out.println("£20");
break;
case "Newcastle":
System.out.println("£65");
break;
case "Cambridge":
System.out.println("£70");
break;
case "Bradford":
System.out.println("£75");
break;
case "Leeds":
System.out.println("£80");
break;
case "Oxford":
System.out.println("£85");
break;
case "Nottingham":
System.out.println("£90");
break;
case "Peterborough":
System.out.println("£95");
break;
case "Sheffield":
System.out.println("£100");
break;
default:
System.out.println("ERROR: INVALID INPUT");
break;
}
} while (answer != "exit");
}
}
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());
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.
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.
When I update the balance of certain record in the array, using the deposit and withdraw amounts, the balance for that sepcific record changes along with the balance for the records in arrays.
How to fix it?
private String name;
private int pin;
private int account;
private static double balance;
public void setBalance(double amount)
{
balance = amount;
}
public static void deposit(double aDeposit)
{
balance = balance + aDeposit;
}
public static void withdraw(double aWithdraw)
{
if
( balance >= aWithdraw)
balance = balance - aWithdraw;
else if
( balance < aWithdraw)
System.out.println("Cannot withdarw amount.");
}
public double getBalance( )
{
return balance;
}
public boolean equal(CustomerRecord otherObject)
{
return (name.equalsIgnoreCase(otherObject.name) &&
(pin == otherObject.pin) &&
(account == otherObject.account) &&
(balance == otherObject.balance));
}
}
do{
System.out.println("Enter the name");
String aName;
Scanner keyboard = new Scanner(System.in);
aName = keyboard.nextLine();
System.out.println("Enter the pin");
int aPin;
aPin = keyboard.nextInt();
for
(int i = 0; i < index; i++) {
CustomerRecord record = anotherArray[i];
if
((record.getName().equalsIgnoreCase(aName)) && (record.getPin() == (aPin)))
{
System.out.println(record);
System.out.println("Enter the amount you wish to Deposit");
double aDeposit;
aDeposit = keyboard.nextDouble();
CustomerRecord.deposit(aDeposit);
System.out.println("Enter the amount you wish to withdraw");
double aWithdraw;
aWithdraw = keyboard.nextDouble();
CustomerRecord.withdraw(aWithdraw);
record.getBalance();
}
}
System.out.println("\nAnother Transaction? (y for yes) (n for no)");
repeat = keyboard.next().charAt(0);
}
while
(
repeat == 'y' || repeat == 'Y') ;
//Print the records on screen
{ for (int i = 0; i < index; i++)
System.out.print(anotherArray[i]);
}
You haven't shown where you define the balance field but going by the fact that you are able to access it from a static methods deposit and withdraw I would guess it is itself a static variable, say
private static double balance;
Now, what does the static mean here? If you figure that out, you will know what is the error in your program, and why changing it in one object changes it in all