I would like someones expert opinion on both of my account class and the test account interest class. The issue I am facing is that the code from the test account interest class just multiplies on from the previous 12 month compute interest when it is supposed to be used only once.
The issue is in the
public double computeInterest(int n)
{
balance=balance*(Math.pow((1+rate),n/12));
return balance;
}
It is in this method of where the problem is that I should not use the balance but to use a variable that will store the answer but I did not understand the person that very clearly and he was very vague by only stating a variable should be used.
public class Account
{
private double balance; //STATE
private double interestRate; //STATE
private double rate;//STATE
public Account()
{
balance = 0;
interestRate = 0;
}
public Account(double amount, double interestRate)
{
balance = amount;
rate = interestRate;
}
public void deposit(double amount)
{
balance=balance+amount;
}
public void withdraw(double amount)
{
balance = balance - amount;
}
public void setInterest(double rate)
{
balance = balance + balance * rate;
//this.setInterst = setInterest;
//setInterest = InterestRate / 12;
}
public double computeInterest(int n)
{
balance=balance*(Math.pow((1+rate),n/12));
return balance;
}
public double getsetInterest()
{
return rate;
}
public double getBalance()
{
return balance;
}
public void close()
{
balance =0;
}
}
This is my test account interest class:
public class TestAccountInterest
{
public static void main (String[] args)
{
Account acc1 = new Account(100, 0.1);//0.10);
Account acc2 = new Account(133, 0.2); //0.20);
/*************************************
ACC1 ACCOUNT BELOW
*************************************/
//acc1.deposit(100);
//acc1.withdraw(100);
System.out.println(acc1.computeInterest(12));
// //acc1.computeInterest(12);
// System.out.println(acc1.computeInterest(24));
/**************************************
ACC2 ACCOUNT BELOW
**************************************/
acc2.withdraw(100);
acc2.deposit(100);
//acc2.computeInterest(24);
System.out.println(acc2.computeInterest(24));
}
}
This is the final output:
110.00000000000001
191.51999999999998
As you can see for the second one the figure is multiplied by the 12 month compute interest with the 24 month compute interest this stems from the method in the account class:
public double computeInterest(int n)
{
balance=balance*(Math.pow((1+rate),n/12));
return balance;
}
If I take out the balance it still causes and error so I confused on this particular part.
Code,
public double computeInterest(int n) {
balance = balance * (Math.pow((1 + rate), n / 12));
return balance;
}
should be changed to
public double computeInterest(int n) {
return balance * Math.pow(1 + rate, n / 12);
}
You shouldn't change balance field while computing interest. You might like to have a separate method to update balance where you do , balance = balance + computed_interest or something like that.
Also, I have remove unnecessary parenthesis. That was not an error but simply making your code less readable.
Related
I have an assignment which asks for everything I have in the code below. That all works fine - I just need to calculate any monthly hours over 160 hours to be paid at 1.5 times the normal hourly rate. My math seems sound and calculates fine:
((hours - 160) * overtime) + (160 * hourlyRate)
But I dont know if I'm putting this if statement in the right method or if it even should be an if statement. My increase/decreasePay methods are working prior to this and they need to stay. I removed some things so it's easier to read.
HourlyWorker Class:
public class HourlyWorker extends Employee
{
private int hours;
private double hourlyRate;
private double monthlyPay;
private double overtime = (1.5 * hourlyRate);
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)
{
this.hourlyRate = rate;
}
public double getHourlyRate()
{
return hourlyRate;
}
public double getMonthlyPay()
{
if (hours > 160)
{
monthlyPay = ((hours - 160) * overtime) + (160 * hourlyRate);
}
else
{
monthlyPay = hourlyRate * hours;
}
return monthlyPay;
}
public void increasePay(double percentage)
{
hourlyRate *= 1 + percentage / 100;
}
public void decreasePay(double percentage)
{
hourlyRate *= 1 - percentage / 100;
}
}
What I'm testing with:
public class TestEmployee2
{
public static void main(String[] args)
{
Employee [] staff = new Employee[3];
HourlyWorker hw1 = new HourlyWorker("Bee", "Busy", "BB1265", 10);
hw1.setHours(200);
staff[0] = hw1;
System.out.println(staff[0].getMonthlyPay());
staff[0].increasePay(10);
System.out.println(staff[0].getMonthlyPay());
}
}
Output is:
1600 (initial monthly rate, with 40 overtime hours and 160 regular hours)
1760 (10% increase to the monthlyPay)
Should be:
2006
2206.6
You code has the following issues:
Field initializers run before the body of the constructor, so overtime = (1.5 * hourlyRate) uses the default value of 0 for the hourlyRate field, calculating an overtime value of 0, and is never recalculated, since initializers only run once, during initialization.
setHourlyRate() updates the hourlyRate field, but doesn't re-calculate the value for the overtime field. Same for increasePay() and decreasePay().
There is no point to the monthlyPay field, since you never really use it, given that you only use it as-if it was a local variable in the getMonthlyPay() method.
Get rid of fields monthlyPay and overtime, and make them both local variables in the getMonthlyPay() method.
FYI: Using double for currency amounts is discouraged. The recommended type for currency in Java is BigDecimal.
Here my code.
Main SavingsDemo.java
public class SavingsDemo
{
public static void main(String[] args)
{
// Create a SavingsAccount object with a $100 balance,
// 3% interest rate, and a monthly service charge
// of $2.50.
SavingsAccount savings =
new SavingsAccount(100.0, 0.03, 2.50);
// Display what we've got.
System.out.printf("Balance: $%,.2f\n",
savings.getBalance());
System.out.println("Number of deposits: " +
savings.getNumDeposits());
System.out.println("Number of withdrawals: " +
savings.getNumWithdrawals());
System.out.println();
// Make some deposits.
savings.deposit(25.00);
savings.deposit(10.00);
savings.deposit(35.00);
// Display what we've done so far.
System.out.printf("Balance: $%,.2f\n",
savings.getBalance());
System.out.println("Number of deposits: " +
savings.getNumDeposits());
System.out.println("Number of withdrawals: " +
savings.getNumWithdrawals());
System.out.println();
// Make some withdrawals.
savings.withdraw(100.00);
savings.withdraw(50.00);
savings.withdraw(10.00);
savings.withdraw(1.00);
savings.withdraw(1.00);
// Display what we've done so far.
System.out.printf("Balance: $%,.2f\n",
savings.getBalance());
System.out.println("Number of deposits: " +
savings.getNumDeposits());
System.out.println("Number of withdrawals: " +
savings.getNumWithdrawals());
System.out.println();
// Do the monthly processing.
savings.monthlyProcess();
// Display what we've done so far.
System.out.printf("Balance: $%,.2f\n",
savings.getBalance());
System.out.println("Number of deposits: " +
savings.getNumDeposits());
System.out.println("Number of withdrawals: " +
savings.getNumWithdrawals());
}
}
Superclass BankAccount.java
public class BankAccount
{
private double balance; //The balance in the account
private int numDeposits; //Number of deposits this month
private int numWithdrawals; //Number of withdrawals
private double interestRate; //Annual interest rate
private double monthlyServiceCharge; //Monthly service charge
/**
The constructor
Accept arguments for the balance and annual interest rate.
#param bal To hold the number of balance.
#param intRate To hold the number of annual interest rate.
#param mon To hold the number of monthly service charge.
*/
public BankAccount(double bal, double intRate, double mon)
{
balance = bal;
interestRate = intRate;
monthlyServiceCharge = mon;
}
/**
This method to hold the amount of deposit.
#param amount The amount of deposit.
*/
public void deposit(double amount)
{
balance = balance + amount;
numDeposits++;
}
/**
This method to hold the amount of withdrawal.
#param amount The amount of withdrawal.
*/
public void withdraw(double amount)
{
balance = balance - amount;
numWithdrawals++;
}
/**
This method to update the balance by calculating the monthly interest
earned by the account.
*/
private void calcInterest()
{
double monIntRate;
double monInt;
monIntRate = (interestRate / 12.0);
monInt = balance * monIntRate;
balance = balance + monInt;
}
/**
This method to calculate the monthly service charge.
*/
public void monthlyProcess()
{
balance = balance - monthlyServiceCharge;
calcInterest();
numWithdrawals = 0;
numDeposits = 0;
monthlyServiceCharge = 0;
}
/**
This method to hold the number of monthly service charge.
#param amount The number of monthly service charge.
*/
public void setMonthlyServiceCharges(double amount)
{
monthlyServiceCharge += amount;
}
/**
This method to return the amount of balance.
#return The amount of balance.
*/
public double getBalance()
{
return balance;
}
/**
This method to return the number of deposits.
#return The number of deposits.
*/
public int getNumDeposits()
{
return numDeposits;
}
/**
This method to return the number of withdrawals.
#return The number of withdrawals.
*/
public int getNumWithdrawals()
{
return numWithdrawals;
}
/**
This method to return the number of annual interest rate.
#return The number of annual interest rate.
*/
public double getInterestRate()
{
return interestRate;
}
/**
This method to return the amount of monthly service charge.
#return The amount of monthly service charge.
*/
public double getMonthlyServiceCharge()
{
return monthlyServiceCharge;
}
}
Subclass SavingsAccount.java
public class SavingsAccount extends BankAccount
{
private boolean status;
/**
The constructor
To accept the argument of balance, interest rate and monthly charge.
#param bal To hold the amount of balance.
#param intRate To hold the number of annual interest rate.
#param mon To hold the amount of monthly service charge.
*/
public SavingsAccount(double bal, double intRate, double mon)
{
super(bal, intRate, mon);
if (bal < 25)
{
status = false;
}
else
{
status = true;
}
}
/**
This method to determine whether the account is inactive before withdrawals
is made.
#param amount The amount of withdrawal.
*/
public void withdraw(double amount)
{
if (status = true)
{
super.withdraw(amount);
}
}
/**
This method to determine whether the account is inactive before a
deposit is made.
#param amount The amount of deposit.
*/
public void deposit(double amount)
{
if (status = true)
{
super.deposit(amount);
}
}
/**
This method to check the number of withdrawals.
*/
public void monthlyProcess()
{
if (getNumWithdrawals() > 4)
{
setMonthlyServiceCharges(getNumWithdrawals() - 4);
}
super.monthlyProcess();
if (getBalance() < 25)
{
status = false;
}
}
}
As the question above. I want to make only two withdraw because in the main program when I do 2 withdraw, the balance will become 20$ and it become inactive. But somehow my code did withdraw 5 times. So can someone give me an idea how to solve this problem. Thanks!
Change
public SavingsAccount(double bal, double intRate, double mon)
{
super(bal, intRate, mon);
if (bal < 25)
{
status = false;
}
else
{
status = true;
}
}
to
public void withdraw(double amount)
{
if (getBalance() > 25)
{
super.withdraw(amount);
}
}
and
public void withdraw(double amount)
{
if (status = true)
{
super.withdraw(amount);
}
}
to
public void withdraw(double amount)
{
if (getBalance() > 25)
{
super.withdraw(amount);
}
}
I'm having a problem which I cannot fathom why. I have program I'm making where it takes a few inputs and calculates pay, tax, and final pay.
Everything is working except the final pay.
this calculates the final pay
import java.util.*;
public class Payroll extends Pay
{
public double calc_payroll()
{
super.calc_payroll();
super.tax();
netPay = grossPay - (grossPay * (tax/100));
return netPay;
}
}
this calculates pay and tax
import java.util.*;
public class Pay
{
private float hoursWrkd;
private float rate;
private int hoursStr;
float grossPay;
int tax;
float netPay;
public double calc_payroll()
{
grossPay = getHoursWrkd()*getRate();
return grossPay;
}
public double tax()
{
if (grossPay <= 399.99)
{
tax = 7;
}
else if (grossPay >= 400.00 && grossPay <= 899.99)
{
tax = 11;
}
else if (grossPay <= 900.00)
{
tax = 15;
}
return tax;
}
//Get & Set for hours worked
public float getHoursWrkd()
{
return hoursWrkd;
}
public void setHoursWrkd(float hoursWrkd)
{
this.hoursWrkd = hoursWrkd;
}
//Get & Set for Rate
public float getRate()
{
return rate;
}
public void setRate(float rate) {
this.rate = rate;
}
//Get & Set for hours straight
public int getHoursStr()
{
return hoursStr;
}
public void setHoursStr(int hoursStr)
{
this.hoursStr = hoursStr;
}
}
and this displays all
public class CalPayroll extends Pay
{
public void displayInfo()
{
super.calc_payroll();
super.tax();
Payroll colio = new Payroll();
colio.calc_payroll();
NumberFormat dollars = NumberFormat.getCurrencyInstance();
System.out.println("Gross Pay is : " + dollars.format(grossPay));
System.out.println("Tax is : " + tax + "%");
System.out.println("Net Pay is : " + dollars.format(netPay));
}
i have more files but those are the ones that just take the input, and call the other files.
The math is correct, however when i try to call the netPay variable and format it, it dosn't display any ammount. With grosspay it works. However my teacher said were supposed to pass grosspay into tax so it can use it, im not sure if that would fix it.
PLease help.
You try to display the netPay from CalPayroll, but this class never computes this value. When you do
Payroll colio = new Payroll();
colio.calc_payroll();
You’re probably expecting the netPay to be calculated in CalPayrool, but you’re actually calculating a separate value in a separate object, which has no effect on the current object.
I have a very basic BankAccount class and tester.
/** A bank account that has a balance that can be changed by depositing and withdrawals also deducts a fee for each withdrawal and deposit.
*
* #author lapenta1
*
*/
public class BankAccount
{
private double balance;
private double feeCharge;
/** Contructs a bank account with a balance of zero
*
*/
public BankAccount()
{
balance = 0;
feeCharge = 2.50;
}
/**Constructs a bank account with a given balance
*
* #param initialBalance the initial balance
*/
public BankAccount(double initialBalance)
{
balance = initialBalance;
}
/** Deposits money into the bank account
*
* #param amount the amount to deposit
*/
public void deposit(double amount)
{
balance = balance + amount - feeCharge;
}
/**Withdrawals money from the bank account
*
* #param amount the amount to withdrawal
*/
public void withdraw(double amount)
{
balance = balance - amount - feeCharge;
}
/**Gets the current balance of the bank account
*
* #return the current balance
*/
public double getBalance()
{
return balance;
}
public void deductMonthlyCharge()
{
}
}
This is the tester class
public class BankAccountTester
{
public static void main(String[] args)
{
BankAccount myWallet = new BankAccount();
myWallet.deposit(200);
System.out.println(myWallet.getBalance());
BankAccount otherWallet = new BankAccount();
otherWallet.deposit(200);
System.out.println(otherWallet.getBalance());
}
}
now I am trying to make it work so there is basically a set amount of withdrawals/deposits that can be used before the 2.50 fee is taken away every month. The only hint I have is to use math.max(actual transaction count, free transaction count) I am lost! any help?
Something like this would do the trick. Just add another if condition(s) to make same for deposits etc.
private int noOfWithdrawals = 0;
private int tresholdOfWithdrawals = 5; //Change this according to your requirement
public void withdraw(double amount)
{
if(noOfWithdrawals <= tresholdOfWithdrawals) {
balance = balance - amount;
noOfWithdrawals++;
}
else {
balance = balance - amount - feeCharge;
}
}
private double balance;
private double feeCharge;
private double freeCharge; // mutator for how many times it will be free
private double trCount = 0; //should increment after every transaction
public double deductMonthlyCharge(){
double monthlyCharge = (Math.max(trCount, freeCharge) - freeCharge) * feeCharge;
balance -= monthlyCharge;
trCount = 0;
return balance;
}
public class AccountDriver {
public static void main(String[] args) {
// ID, Balance, Annual Interest Rate
Account number1 = new Account();
Account number2 = new Account(1122, 20000.00, 0.045);
// Default account
System.out.println("The Account ID is: " + number1.getId());
System.out.println("The Account Balance is: " + number1.getBalance());
// System.out.println("The Account Balance is: "+
// number1.getMontlyInterest());
System.out.println("");
// Ask to withdraw 2500
System.out.println("The Account ID is: " + number2.getId());
number2.withdraw(2500.00);
number2.deposit(3000.00);
System.out.println("Account Balance is " + number2.getBalance());
// System.out.println("The montly interest is : "+
// number2.getMontlyInterest());
System.out.println("");
}
}
public class Account {
private int id = 0;
private double balance = 0;
private double annualInterestRate = 0;
public Account(int id, double balance, double annualInterestRate) {
this.setId(id);
this.setBalance(this.balance);
this.setBalance(annualInterestRate);
}
public Account() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public double getAnnualInterestRate() {
return annualInterestRate;
}
public void setAnnualInterestRate(double annualInterestRate) {
this.annualInterestRate = annualInterestRate;
}
public double getMontlyInterest(double montlyInterest) {
// Given Formula
// double MontlyInterest= this.balance * get.MontlyInterestRate();
return montlyInterest;
}
public double getMontlyInterestRate(double montlyInterestRate) {
// Given Formula
montlyInterestRate = this.annualInterestRate / 12;
return montlyInterestRate;
}
double withdraw(double amount) {
return balance -= amount;
}
double deposit(double amount) {
return balance += amount;
}
}
I am getting error
The Account ID is: 0
The Account Balance is: 0.0
The Account ID is: 1122
Account Balance is 20500.0
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method getMontlyInterestRate(double) in the type Account is not applicable for the arguments ()
at Account.getMontlyInterest(Account.java:41)
at AccountDriver.main(AccountDriver.java:21)
You did 2 small mistakes in your code.
In your constructor these 2 lines
this.setBalance(this.balance); // this.balance is the instance variable and not the parameter passed
^^^^ - this is not required, just use the balance parameter passed.
this.setBalance(annualInterestRate); // you are re-writing the balance with interest rate
^^^^^^^^^^ - You need to set annual interest rate and not the balance here.
should be
this.setBalance(balance); // sets the balance passed to the instance variable balance
this.setAnnualInterestRate(annualInterestRate); // sets the annual interest rate
Now since the annualInterestRate is set, you can get the monthly interest rate by modifying getMontlyInterestRate method like this.
public double getMontlyInterestRate() {
// Given Formula
return this.annualInterestRate / 12;
}
And you can print your monthly interest rate by uncommenting your System.out.println code.
System.out.println("The montly interest is : "+ number2.getMontlyInterestRate());
And the monthly interest method would look like this:
public double getMontlyInterest() { // no parameter required
// Given Formula
double MontlyInterest = this.balance * getMontlyInterestRate(); // balance multiplied by monthly interest rate
return MontlyInterest; // return the value
}
System.out.println("The montly interest is : "+ number2.getMontlyInterest());