I'm having a bit of an issue with a school project of mine. We're supposed to write a Loan class that will do things associated with, well, loans, such as return the monthly payment and the total payment on the loan. My problem is that I have specific instructions for this code that I absolutely cannot go outside of.
Here's the code:
import java.util.Scanner;
import java.text.DecimalFormat;
import java.lang.Math;
public class Loan
{
public double annualInterestRate = 0;
public int numberOfYears = 0;
public double loanAmount = 0;
public Loan()
{
annualInterestRate = 0.025;
numberOfYears = 1;
loanAmount = 1000;
}
public Loan(double interestRate, int numYears, double amount)
{
setRate(interestRate);
setYears(numYears);
setLoanAmount(amount);
}
public void setRate(double interest)
{
DecimalFormat percent = new DecimalFormat( "0.0%" );
if(interest > 25 || interest < 0)
{
System.out.println("WARNING: Invalid annual interest rate: " + percent.format(interest) + ".");
System.out.println("Current value not changed: " + percent.format(annualInterestRate * 100) + ".");
}
else
{
annualInterestRate = interest;
}
}
public void setYears(int years)
{
if(years > 30 || years <= 0)
{
System.out.println("WARNING: Invalid number of years: " + years + ".");
System.out.println("Current value not changed: " + numberOfYears + ".");
}
else
{
numberOfYears = years;
}
}
public void setLoanAmount(double amnt)
{
DecimalFormat loan = new DecimalFormat( "$#,##0.00" );
if(amnt <= 0)
{
System.out.println("WARNING: Invalid loan amount: " + loan.format(amnt) + ".");
System.out.println("Current value not changed: " + loan.format(amnt) + ".");
}
else
{
loanAmount = amnt;
}
}
public double getAnnualInterestRate()
{
return annualInterestRate;
}
public int getNumberOfYears()
{
return numberOfYears;
}
public double getLoanAmount()
{
return loanAmount;
}
public double getMonthlyPayment()
{
double monthly = annualInterestRate/12;
double monthlyPayment = (loanAmount * monthly)/1 - (1/(1 + monthly));
monthlyPayment = Math.pow(monthlyPayment, 12);
return monthlyPayment;
}
public double getTotalPayment()
{
double totalPayment = getmonthlyPayment() * 12;
return totalPayment;
}
public String toString()
{
DecimalFormat percent = new DecimalFormat( "0.0%" );
DecimalFormat loan = new DecimalFormat( "$#,##0.00" );
String interestRate = percent.format(annualInterestRate);
String numOfYears = Integer.toString(numberOfYears);
String loanAmnt = loan.format(loanAmount);
String total = "Annual Interest Rate:\t" + interestRate + "\nNumber of Years:\t\t" + numOfYears + "\nLoan Amount:\t\t\t" + loanAmnt;
return total;
}
}
My problem is with the getTotalPayment method. It can't access the monthlyPayment variable without me either declaring monthlyPayment as a field, like annualInterestRate, or passing it to the getTotalPayment method. The issue is, getTotalPayment is not allowed to have parameters, and we aren't allowed to have any more fields than the three she instructed us to have, which are the three you'll see declared in the beginning of the code.
So, my question: is there a way to make the variable monthlyPayment accessible to getTotalPayment, without making monthlyPayment a field or giving getTotalPayment a parameter?
You have a spelling error in your getTotalPayment() method.
What your trying to do is call the method getmonthlyPayment() when you should be calling getMonthlyPayment().
Incase you missed the suttle difference in my answer you have a lowercase 'm' when you want an uppercase 'M'.
Im not entirety sure if this is your problem, but its the only syntax error my IDE is telling me.
In your revised code you need upper case M in call to getMonthlyPayment().
Related
Why does my text file print the code backward? I need it to print the loan balance decreasing from top to bottom. I didn't include the program that will call the methods, let me know if I should post that as well.
Also, if there are any other discrepancies anyone might see, let me know. Thank you!
package amortizationpack;
import java.io.*;
import java.util.Scanner;
import java.lang.Math;
import java.text.DecimalFormat;
public class Amortization {
double loanAmount;
double interestRate;
double loanBalance;
double term;
double payment;
int loanYears;
Scanner keyboard = new Scanner(System.in);
DecimalFormat number = new DecimalFormat("#,##0.00");
public Amortization(double userLoanAmount, int userLoanYears, double userInterestRate) {
loanAmount = userLoanAmount;
loanYears = userLoanYears;
interestRate = userInterestRate;
calcPayment();
} // constructor
public void calcPayment() {
term = (Math.pow((1 + interestRate / 12), (loanYears * 12)));
payment = (loanAmount * (interestRate / 12) * term) / (term - 1);
} // calcPayment method
public int getNumberOfPayments() {
return loanYears * 12;
} // getNumberofPayments
public void saveReport(String loanFile) throws IOException{
double monthlyInterest;
double principal;
File file = new File("LoanReport.txt");
FileWriter fileWrite = new FileWriter(file);
PrintWriter outputFile = new PrintWriter(fileWrite);
outputFile.println("Monthly payment: " + number.format(payment));
outputFile.println("Month\t\t" + "Interest\t\t" + "Principal\t\t"
+ "Balance");
outputFile.println("--------------------------------------------"
+ "-------------------");
for (int m = 1; m <= getNumberOfPayments(); m++) {
monthlyInterest = interestRate / 12.0 * loanBalance;
if (m != getNumberOfPayments()) {
principal = payment - monthlyInterest;
}
else {
principal = loanBalance;
payment = loanBalance + monthlyInterest;
} // for last payment
loanBalance = loanBalance - principal;
outputFile.print(m + "\t\t"
+ number.format(monthlyInterest) + "\t\t" + number.format(principal) + "\t\t"
+ number.format(loanBalance) + "\n");
} // for loop for writing data to text file
outputFile.close();
System.out.print("File Created");
} // saveReport
} // class
I don't see an answer yet, maybe the way you are printing the values along the getNumberOfPayments() value, but correct me if I'm wrong: you are using the loanBalance variable before assigning it a value.
This answer was in the comments so I don't think I could use it as an official answer, credit goes to user16320675.
Basically, I didn't initialize the loanBalance variable, so it was iterating into the negative numbers from zero, instead of decreasing from the starting balance.
Having trouble compiling these two files to run together.
I get a "can't find or load main class" error or a "erroneous tree" error.
Never asked for help on here before, hope this works :)
package savingsaccount;
import java.util.Scanner;
public class SavingsAccount
{
public static void main(String[] args)
{
double begginingBalance, deposit, withdraw;
int months;
double monthlyRate;
double plus = 0.0;
double minus = 0.0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the balance at beggining of " +
"accounting period.");
begginingBalance = keyboard.nextDouble();
System.out.println("Please enter number of months in current " +
"accounting period.");
months = keyboard.nextInt();
System.out.println("Enter the annual interest rate.");
monthlyRate = keyboard.nextDouble();
a7main accounting = new a7main();
for(int month = 1; month<=months; month++)
{
System.out.println("Enter the amount of deposits for month " +
month + " : ");
plus = keyboard.nextDouble();
accounting.deposits(plus);
System.out.println("Enter the amount of withdrawals for" +
" month " + month + ": ");
minus = keyboard.nextDouble();
accounting.withdrawals(minus);
accounting.interest(monthlyRate);
}
System.out.println("The account balance is: " +
accounting.getBalance());
System.out.println("The total amount of deposits is:" + plus);
System.out.println("The total amount of withdrwals is: " + minus);
System.out.println("The earned interest is: " +
accounting.getRate());
}
}
HERE IS THE CLASS FILE
I am trying to use the methods in this file to calculate and hold the values from the other file.
public class a7main
{
private double totalBalance;
private double interestRate;
public a7main(double balance,double rate)
{
totalBalance = balance;
interestRate = rate;
}
public void deposits(double deposit)
{
totalBalance = totalBalance+deposit;
}
public void withdrawals(double withdraw)
{
totalBalance = totalBalance-withdraw;
}
public void interest(double rate)
{
interestRate = totalBalance*rate;
}
public double getBalance()
{
return totalBalance;
}
public double getRate()
{
return interestRate;
}
}
#Alex Goad -
Add package name in a7main class
You have created parameterized constructor and no default constructor.
a7main accounting = new a7main();
The above line will look for default constructor like
public a7main(){
}
I'm sure this has a simple solution, but I'm new to Java and can't work it out.
I have a subclass Payroll that extends a superclass Pay, it contains an overridden method called 'calc_payroll'. From this method, I want to call the superclass method of the same name, and assign the output to a variable in the overriding method. My code is below
public class Payroll extends Pay
{
public double calc_Payroll()
{
double grossPay = super.calc_Payroll();
double taxAmt = tax(grossPay);
double netPay = grossPay - taxAmt;
System.out.println(grossPay);
return netPay;
}
}
Below is the code from the calc_payroll method in the superclass
public double calc_Payroll()
{
double otRate = rate * 1.77;
double otHours = ttlHours - stHours;
if(stHours == 0)
{
grossPay = otHours * rate;
}
else
{
grossPay = ((stHours * rate) + (otHours * otRate));
}
System.out.println(stHours + "//" + otHours + "//" + rate);//for testing
return grossPay;
}
the superclass method functions without issue to calculate and return the gross pay when called from a different subclass, but when calling it from a method with the same name, the print line in the code above (that I have labelled for testing) displays zero's for all variables
Code for full 'Pay' class is below as requested
public class Pay
{
private double ttlHours;
private int stHours;
private double rate;
double grossPay = 0.0;
final double TAXL = 0.07;
final double TAXM = 0.1;
final double TAXH = 0.16;
public void SetHours(double a)
{
ttlHours = a;
}
public void SetHoursStr(int a)
{
stHours = a;
}
public void SetRate(double a)
{
rate = a;
}
public double GetHours()
{
return ttlHours;
}
public int GetStHours()
{
return stHours;
}
public double GetRate()
{
return rate;
}
public double taxRate()
{
double taxRate = 0.0;
if(grossPay <= 399.99)
{
taxRate = TAXL;
}
else if(grossPay <= 899.99)
{
taxRate = TAXM;
}
else
{
taxRate = TAXH;
}
return taxRate;
}
public double tax(double grossPay)
{
double ttlTax = 0.0;
if(grossPay < 400.00)
{
ttlTax += (grossPay * TAXL);
}
else if(grossPay < 900.00)
{
ttlTax += (grossPay * TAXM);
}
else
{
ttlTax += (grossPay * TAXH);
}
return ttlTax;
}
public double calc_Payroll()
{
double otRate = rate * 1.77;
double otHours = ttlHours - stHours;
if(stHours == 0)
{
grossPay = otHours * rate;
}
else
{
grossPay = ((stHours * rate) + (otHours * otRate));
}
System.out.println(stHours + "//" + otHours + "//" + rate);//for testing
return grossPay;
}
}
The subclass Payroll contains no other code
Below is the code that accepts user input to assign values to the initialized variables
public class CalPayroll extends Pay
{
Payroll nPay = new Payroll();
Accept Read = new Accept();
public void AcceptPay()
{
char select = '0';
while(select != 'e' && select != 'E')
{
System.out.println("Payroll Computation \n");
System.out.print("Enter number of hours worked (00.0) <0 for Quick exit>: ");
SetHours(Read.AcceptInputDouble());
System.out.print("Enter first number of hours straight (integer or 0 to disable): ");
SetHoursStr(Read.AcceptInputInt());
System.out.print("Enter hourly rate of worker (00.00): ");
SetRate(Read.AcceptInputDouble());
Screen.ScrollScreen('=', 66, 1);
Screen.ScrollScreen(1);
displayInfo();
System.out.println("e to exit, any other letter + <Enter> to continue");
select = Read.AcceptInputChar();
}
}
public void displayInfo()
{
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
System.out.println("Gross pay is :" + currency.format(calc_Payroll()));
System.out.println("Tax is :" + percent.format(taxRate()));
System.out.println("Net pay is :" + currency.format(nPay.calc_Payroll()));
Screen.ScrollScreen(1);
}
}
I'm confused!
Its clear from you code that ttlHours, stHours and rate are not initialised with some reasonable value. So when you just call super.calc_Payroll(), values like 0 or 0.0 are used as i explained in my comment. Its good to first set values of these variables before calling super.calc_Payroll().
SetHours(23.4); //some value
SetHoursStr(5); //some value
SetRate(2.3); //some value
Also you don't have constructor for Pay class, try making it and initialising all uninitialised variable in constructor or use setter/getter methods to set and get values.
Since your both classes extends Pay class, it creates the problem which you are facing. When you call SetHours(Read.AcceptInputDouble()), it set the variable inherited by CalPayroll from Pay, not the variables inherited by Payroll class. What you have to do is to set variables for Payroll instance as well as for current class as both extends Pay. Do the following replace your while loop as,
while(select != 'e' && select != 'E')
{
System.out.println("Payroll Computation \n");
System.out.print("Enter number of hours worked (00.0) <0 for Quick exit>: ");
SetHours(Read.AcceptInputDouble());
nPay.SetHours(GetHours());
System.out.print("Enter first number of hours straight (integer or 0 to disable): ");
SetHoursStr(Read.AcceptInputInt());
nPay.SetHoursStr(GetStHours());
System.out.print("Enter hourly rate of worker (00.00): ");
SetRate(Read.AcceptInputDouble());
nPay.SetRate(GetRate());
Screen.ScrollScreen('=', 66, 1);
Screen.ScrollScreen(1);
displayInfo();
System.out.println("e to exit, any other letter + <Enter> to continue");
select = Read.AcceptInputChar();
}
Please post the complete code.
It seems that for some reason your variables of super class method not getting assigned values properly. And they are initialized with their default values which is making everything 0. I'll be able to help better if you paste the complete class.
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.
This will be my second question on here; I try not to ask because I don't fancy receiving help for my homework. But I'm just plain stuck.
I'm currently writing a program that stores and updates information for some example bank accounts. My issue is that, somehow, my output has two decimal points.
Example:
"2000.02008.3333333333333"
Side notes: I'm in a Tier II java course, so yes, my code isn't the prettiest. Also, please only offer hints as to where I should make changes. As I said earlier, I try really hard not to ask for help and I don't want my request for help to be misconstrued as cheating. Finally, I do know about syso formatting and will be doing that with the Title information in my driver. The way I did it in there was just faster for me at the time while I fleshed out the rest of the details.
Many thanks in advance to any help provided!
Here's my current code:
public class SavingsAccount
{
private static double annualInterestRate;
private final int ACCOUNT_NUMBER;
private double balance;
public SavingsAccount(int ACCOUNT_NUMBER, double balance)
{
this.ACCOUNT_NUMBER = ACCOUNT_NUMBER;
this.balance = balance;
}
public static double setAnnualInterestRate(double aIR)
{
annualInterestRate = aIR;
return annualInterestRate;
}
public int getAccountNumber()
{
return ACCOUNT_NUMBER;
}
public double getBalance()
{
return balance;
}
public double addMonthlyInterest()
{
balance += (balance * annualInterestRate / 12);
return balance;
}
}
DRIVER
public class Chapter13
{
public static void main(String[] args)
{
double annualInterestRate = .05;
SavingsAccount saver1 = new SavingsAccount(10002, 2000);
SavingsAccount saver2 = new SavingsAccount(10003, 3000);
SavingsAccount.setAnnualInterestRate(annualInterestRate);
System.out.println("Month Acount# Balance Account# Balance");
for(int i = 0; i < 13; i++)
{
System.out.println(i + " " + saver1.getBalance() +
saver1.addMonthlyInterest());
}
}
}
That's because the balance and annualInterestRate are getting printed without any space between them. Add a tab or space between them so that they are printed separately.
System.out.println(i + " " + saver1.getBalance() + "\t" // tab
saver1.addMonthlyInterest());
System.out.println(i + " " + saver1.getBalance() + " " // space
saver1.addMonthlyInterest());