Calling a method that only prints out a "loan statement" - java

I am doing an assignment for class and we just started making our own methods and what I thought seemed easy enough has become extremely frustration and hoping you can help me wrap my head around it.
First things first and the assignment I am trying to complete is this: make a modular program to calculate monthly payments, seems easy but the few restrictions on this question is as follows
The main method should:
Ask the user for
the loan amount
the annual interest rate ( as a decimal, 7.5% is 0.075 )
the number of months
And
call a method to calculate and return the monthly interest rate (annual rate/12)
call a method to calculate and return the monthly payment
call a method to print a loan statement showing the amount borrowed, the annual interest rate, the number of months, and the monthly payment.
I have gotten to the end of just printing out the loan statement but cant for the life of me the proper way to call it, and make it show up once I run the program :/ so if you can help me understand how its done I would greatly appreciate it.
(I realize that there are probably other mistakes in my code but for right now I would rather just focus on what I need to get done)
import java.util.Scanner;
public class LoanPayment {
/**
* The main method declares the variables in program while getting the user
* info of amount loaned, interest rate of the loan, and the loans duration.
*
* The main method also calls other methods to calculate monthly interest
* monthly payments and the output of the loan statement
*/
public static void main(String[] args)
{
// declare variables
double interest; // interest attributed to the loan
double mInterest; // loans interest divided by 12
int time; // how long the loan was taken out for
double principle; // the amount borrowed
double mPayment; // how much is to be paid each month
double loan;
// initate new scanner class
Scanner keyboard = new Scanner(System.in);
// get user input/information
System.out.println("Hi, Please enter the loan amount here:");
principle = keyboard.nextDouble();
System.out.println("Thanks, now what is the annual interest rate in decimal notation" +
"(example: 7.5% is 0.075:");
interest = keyboard.nextDouble();
System.out.println("now please put in the number of months the loan was taken out for");
time = keyboard.nextInt();
// call method to calculate and return monthly interest rate
mInterest = calcMInterest( interest );
// call method to calculate and return the monthly payment
mPayment = calcMPayment (mInterest, principle, time);
// call method to print loan statement
} // end main ()
/******************************************************************************/
// this class calculates and returns the monthly interest on the loan
public static double calcMInterest( double interest )
{
double mInterest;
mInterest = (interest / 12);
return mInterest;
} // end calcMInterest
/******************************************************************************/
// this class calculates and returns the monthly payment
public static double calcMPayment (double mInterest, double principle, int time)
{
double mPayment;
mPayment = (mInterest * principle) / (1-(1+ Math.pow(mInterest,-time)));
return mPayment;
} // end calcMPayment
/******************************************************************************/
// this class prints a loan statement showing the amount borrowed
// and the amount borrowed, the annual interest rate, the number of months
// and the monthly payment
public static void loanStatement(double principle, double interest, int time, double mPayment)
{
System.out.println(" principle is" + principle);

If // call method to print loan statement is all you have left to do, then this is what you need on the line below it:
loanStatement(principle, interest, time, mPayment);
And it should work fine.
Your other methods have non-void return types, so you put someVariable = yourMethod(yourArguments) in order to accept the return value. However, loanStatement has a void return type. You don't need to do this. You can call it simply as I showed above and it will execute the code in the method.
Though, my personal preference would be to change loanStatement to a String return type and put the print statement in main and print the return of loanStatement. Methods that return Strings almost as easily and are more flexible for future use (for example, if you wanted to allow your program to also write to file, you need two loanStatement methods, or to completely rework loanStatement).

Check out this solution ;)
public class LoanStatement{
public static void main(String []args){
// declare variables
double interest; // interest attributed to the loan
double mInterest; // loans interest divided by 12
int time; // how long the loan was taken out for
double principle; // the amount borrowed
double mPayment; // how much is to be paid each month
double loan;
// initate new scanner class
Scanner keyboard = new Scanner(System.in);
// get user input/information
System.out.println("Hi, Please enter the loan amount here:");
principle = keyboard.nextDouble();
System.out.println("Thanks, now what is the annual interest rate in decimal notation" +
"(example: 7.5% is 0.075:");
interest = keyboard.nextDouble();
System.out.println("now please put in the number of months the loan was taken out for");
time = keyboard.nextInt();
// call method to calculate and return monthly interest rate
mInterest = calcMInterest( interest );
// call method to calculate and return the monthly payment
mPayment = calcMPayment (mInterest, principle, time);
// call method to print loan statement
loanStatement(principle,interest,time,mPayment);
}
// this method calculates and returns the monthly interest on the loan
public static double calcMInterest( double interest )
{
double mInterest;
mInterest = (interest / 12);
return mInterest;
} // end calcMInterest
// this method calculates and returns the monthly payment
public static double calcMPayment (double mInterest, double principle, int time)
{
double mPayment;
mPayment = (mInterest * principle) / (1-(1+ Math.pow(mInterest,-time)));
return mPayment;
} // end calcMPayment
// this class prints a loan statement showing the amount borrowed
// and the amount borrowed, the annual interest rate, the number of months
// and the monthly payment
public static void loanStatement(double principle, double interest, int time, double mPayment)
{
System.out.println(" principle is" + principle);
}
}

Related

how to create java methods [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Create a class studentBilling() that includes three return overloaded calculateBill() methods as follows:
The first calculateBill() method will receive the tuition fees as single parameter. Add 14% tax to the tuition fees and return the total due.
The second calculateBill() method receives the tuition fees and the cost of textbooks. Add the two values and then add 14% tax and return the total due.
The third calculateBill() method receives the tuition fees, textbook costs and a coupon value. Add the tuition and cost of textbooks and subtract the coupon value. Add 14% tax and return the total due.
Write a program billTesting that tests all three overloaded methods.
Create a new studentBilling object.
Create a Scanner object to enter the tuition fees, textbook costs, and the coupon value.
Call the three methods and display the results.
my solution
package student;
import java.util.Scanner;
/**
*
* #author FASA
*/
public class Student {
double totalDue;
static Scanner fees = new Scanner(System.in);
double Student;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner fees = new Scanner(System.in);
System.out.println(CalculateBill1());
System.out.println(CalculateBill2());
System.out.println(CalculateBill3());
}
public static double CalculateBill1 (double totalDue, double tax, double fees) {
tax = 0.14;
return (totalDue);
}
public double CalculateBill2 (double fees, double textBookFees) {
double tax = 0.14;
Student = fees + textBookFees + tax;
return (totalDue);
}
public double CalculateBill3 (double tax, double fees, double textBookFees, double couponValue) {
Student = fees + textBookFees - couponValue + tax;
return (totalDue);
}
}
It wont print the bill, please help
I am not going to help you with the complete solution as it seems to be your homework ;)
You should get compilation error on lines System.out.println(CalculateBill1());
System.out.println(CalculateBill2());
System.out.println(CalculateBill3()); because there is no method with definition as void parameter.
you need to pass appropriate parameters to call these methods. For example to call method "CalculateBill1 (double totalDue, double tax, double fees)" you need to call it like below:
System.out.println(CalculateBill1(1.25,5.23,6.0));
Hope this help.

Banking interest Q

Im trying to make a program that calculates the compound interest of an account with the principle,interest rate, and years. Im trying to do it with dialogs/ The program has the output the return on the invesment if the principle is left to accumulate.
Im stuck on the calculation part, please help
package firstAssignment;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class thinkingQuestion {
public static void main(String[] args) {
//Banking program that asks user for the amount of money they wish to invest in a
//compound interest account (principle), the interest rate (percent value) and the time frame (years).
Scanner in= new Scanner(System.in);
String principle, interestVal, years;
int newPrinciple,newYears;
double total;
principle=JOptionPane.showInputDialog("How much money would you like to invest?");
interestVal=JOptionPane.showInputDialog("What's the interest rate?");
years=JOptionPane.showInputDialog("How many years?");
//convert from String to integer
newPrinciple=Integer.parseInt(principle);
newYears=Integer.parseInt(years);
double newInterestVal=Integer.parseInt(interestVal);
total=JOptionPane.PLAIN_MESSAGE(newPrinciple*Math.pow(1+ newInterestVal, newYears), newYears);
I deleted somo variables you don't need, I think the main problem is on java syntax for show messages. Here you could see a tutorial:
https://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html
import javax.swing.JOptionPane;
public class InterestBanking {
public static void main(String[] args) {
// Banking program that asks user for the amount of money they wish to
// invest in a
// compound interest account (principle), the interest rate (percent
// value) and the time frame (years).
String principle, interestVal, years;
float newPrinciple, newYears;
principle = JOptionPane.showInputDialog("How much money would you like to invest?");
interestVal = JOptionPane.showInputDialog("What's the interest rate?");
years = JOptionPane.showInputDialog("How many years?");
// convert from String to integer
newPrinciple = Float.parseFloat(principle);
newYears = Float.parseFloat(years);
double newInterestVal = Float.parseFloat(interestVal);
//You could change your calculation here if this isn't the need formula
double interest = newPrinciple * Math.pow(1 + newInterestVal, newYears);
//you were assigning the result to a total variable. That's not neccesary
JOptionPane.showMessageDialog(null, "Interest:" + NumberFormat.getCurrencyInstance(new Locale("en", "US")).format(interest) + " In years: " + newYears);
}
}

Amortization Table

This program will calculate the amortization table for a user. The problem is my assignment requires use of subroutines. I totally forgot about that, any ideas on how to modify this to include subroutines?
public class Summ {
public static void main(String args[]){
double loanamount, monthlypay, annualinterest, monthlyinterest, loanlength; //initialize variables
Scanner stdin = new Scanner (System.in); //create scanner
System.out.println("Please enter your loan amount.");
loanamount = stdin.nextDouble(); // Stores the total loan amount to be payed off
System.out.println("Please enter your monthly payments towards the loan.");
monthlypay = stdin.nextDouble(); //Stores the amount the user pays towards the loan each month
System.out.println("Please enter your annual interest.");
annualinterest = stdin.nextDouble(); //Stores the annual interest
System.out.println("please enter the length of the loan, in months.");
loanlength = stdin.nextDouble(); //Stores the length of the loan in months
monthlyinterest = annualinterest/1200; //Calculates the monthly interest
System.out.println("Payment Number\t\tInterest\t\tPrincipal\t\tEnding Balance"); //Creates the header
double interest, principal; //initialize variables
int i;
/* for loop prints out the interest, principal, and ending
* balance for each month. Works by calculating each,
* printing out that month, then calculating the next month,
* and so on.
*/
for (i = 1; i <= loanlength; i++) {
interest = monthlyinterest * loanamount;
principal = monthlypay - interest;
loanamount = loanamount - principal;
System.out.println(i + "\t\t" + interest
+ "\t\t" + "$" + principal + "\t\t" + "$" + loanamount);
}
}
}
any ideas on how to modify this to include subroutines?
Well, you are better off doing it the other way around; i.e. working out what the methods need to be before you write the code.
What you are doing is a form or code refactoring. Here's an informal recipe for doing it.
Examine code to find a sections that perform a specific task and produces a single result. If you can think of a simple name that reflects what the task does, that it a good sign. If the task has few dependencies on the local variables where it currently "sits" that is also a good sign.
Write a method declaration with arguments to pass in the variable values, and a result type to return the result.
Copy the existing statements that do the task into the method.
Adjust the new method body so that references to local variables from the old context are replaced with references to the corresponding arguments.
Deal with the returned value.
Rewrite the original statements as a call to your new method.
Repeat.
An IDE like Eclipse can take care of much of the manual work of refactoring.
However, the real skill is in deciding the best way to separate a "lump" of code into discrete tasks; i.e. a way that will make sense to someone who has to read / understand your code. That comes with experience. And an IDE can't make those decisions for you.
(And did I say that it is easier to design / implement the methods from the start?)
I deleted my previous comment as I answered my own question by reading the associated tags :-)
As an example, define a method like this in your class:
public double CalculateInterest(double loanAmount, double interestRate) {
//do the calculation here ...
}
And then call the method by name elsewhere in your class code e.g.
double amount = CalculateInterest(5500, 4.7);

Object and Classes: Finding balance ,annual interest rate, monthly interest rate, withdrawing, depositing [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Instructions: Design a class named Account that contains:
A private int data field named id for the account ( default 0).
A private double data field named balance for the account ( default 0).
A private constant double data field named annualInterestRate that stores the current interest rate of 12%. Assume all accounts have the same interest rate.
A private Date data field named dateCreated that stores the date when the account was created.
A no-arg constructor that creates a default account.
A constructor that creates an account with the specified id and initial balance.
The accessor (setter) and mutator (getter) methods for id, balance, and annualInterestRate.
The accessor method for dateCreated.
A method named getMonthlyInterestRate() that returns the monthly interest rate in as a percentage. For example it returns 1, not .01, for a 1% monthly rate.
A method named getMonthlyInterest() that returns the monthly interest.
A method named withdraw that withdraws a specified amount from the account.
A method named deposit that deposits a specified amount to the account.
Create a project file in Bluej and implement the class. ( Hint: The method getMonthlyInterest() is to return monthly interest, not the interest rate. Monthly interest is balance * monthlyInterestRate. monthlyInterestRate is annualInterestRate /1200.
Test the program using BlueJ. You should test each of the methods making sure that they are working properly.
Write a second class called AccountTester which contains the main method. The account tester should do the following in this order:
Create an account object
Display the account balance
Display the annualInterestRate
Deposit $150
Display the account balance
Withdraw $50
Display the account balance
Deposits the monthly interest
Display the account balance
Here is my following code. I have errors I am just not sure how to fix them. Any help/tips would be appreciated
import java.util.Scanner;
import java.util.Date;
public class Account
{
private int id = 0;
private double balance = 0;
final private double annualinterestrate = 0.12;
Date dateCreated;
public Account()
{
}
public Account(int aId, double aBalance, double annualInterestRate)
{
id = aId;
balance = aBalance;
annualInterestRate = annualInterestRate;
dateCreated = new Date();
}
public void setID (int aId)
{
id = aId;
}
public int getID()
{
return id;
}
public void setBalance (double aBalance)
{
balance = aBalance;
}
public double getbalance()
{
return balance;
}
public void setAnnualInterestRate (double aannualInterestRate)
{
annualInterestRate = aannualInterestRate;
}
public double getAnnualInterestRate()
{
return annualInterestRate;
}
public Date getDateCreated()
{
return dateCreated;
}
public double getMonthlyInterestRate()
{
return annualInterestRate / 12;
}
public void withdraw(double amount)
{
balance -= amount;
}
public void deposit(double amount)
{
balance += amount;
}
}
Then here is the second class code which contains the main method:
public class AccountTester
{
public static void main(String[] args)
{
Account account = new Account(1857, 5000, 0.12);
account.setID(1857);
account.setBalance(5000);
account.setAnnualInterestRate(0.12);
System.out.println ("Account number: \n"+ +account.getID());
System.out.println ("The account balance is: $ \n" + +account.getbalance());
System.out.println("The Annual Interest Rate is: $ \n" + account.getannualInteresrRate());
account.deposit(150);
System.out.println("The account balance is: $ \n" +account.getbalance());
account.withdraw(50);
System.out.println("The account balance is: $ \n" +account.getbalance());
System.out.println ("The monthly interest earned is: $ \n" + +account.getbalance() * account.annualInterestRate());
System.out.println ("The account was created on: \n" + +account.getdateCreated());
}
}
Your current issue is that you didn't use camelCasedNames when you defined the annualInterestRate field, so it doesn't exist! It's currently named annualinterestrate instead (note there are no caps!). You ought to rename it to match what you're using elsewhere.
Also, that field in particular has another problem, which is that you've declared it final. That means you can't modify it after the object is created, so your setAnnualInterestRate method is doomed to fail anyway unless you remove the final modifier. So that field declaration should look like this:
private double annualInterestRate = 0.12;
Your naming conventions in general are obviously giving you some serious grief. You indicated in the comments that you don't want to use the this keyword since your instructor hasn't introduced it yet, and that's fine, but you should at least name your variables in some way that it's obvious from looking at it what's going on and whether it will work. Prefixing variable names with a lowercase "a" is not the answer. Instead, consider a meaningful prefix or suffix if you need to avoid naming conflicts. For example:
public void setBalance (double newBalance)
{
balance = newBalance;
}
You've got other spelling errors elsewhere, including in your AccountTester class. You need to go through your code carefully and make sure the names match up exactly. Working with an IDE like Eclipse or NetBeans with live compilation warnings and auto-completion will likely save you a lot of trouble.

(double,int) cannot be applied to (double)

Been wracking my brain for hours trying to figure this out.
i have the main method which is:
public static void main(String [] args)
{
double payRate;
double grossPay;
double netPay;
int hours;
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Pay Roll Program");
printDescription();
System.out.print("Please input the pay per hour: ");
payRate = input.nextDouble();
System.out.println("\nPlease input the pay per hour: ");
hours = input.nextInt();
System.out.println("\n");
netPay = computePaycheck(netPay);
System.out.println("The net pay is $" + (netPay));
System.out.println("We hope you enjoyed this program");
System.exit(0);
and the method that calculated the netPay
public static double computePaycheck(double payRate, int hours)
{
double grossPay = computePaycheck(payRate*hours);
double netPay = (grossPay - (grossPay *.15));
return netPay;
}
But I'm getting the error "computePaycheck(double,int) in PayCheck cannot be applied to (double)"
I sort of understand this, but I can't for the life of me figure out a remedy.
1) You are calling a function with 2 parameters while only passing 1. That will cause a compilation error.
2) When you call computePaycheck from within itself that will loop and cause a stack overflow.
netPay = computePaycheck(netPay);
public static double computePaycheck(double payRate, int hours)
"computePaycheck(double,int) in PayCheck cannot be applied to (double)"
Your method takes two parameters, a double and an int.
You can only call it with those two (you are missing the number of hours in the call).
netPay = computePaycheck(payRate, hours);
double grossPay = payRate*hours;
In your computePaycheck method, you have the following line:
double grossPay = computePaycheck(payRate*hours);
This is passing one parameter (the product of payRate and hours) to the computePaycheck function, which requires two parameters. It looks like you meant to say:
double grossPay = computePaycheck(payRate, hours);
But you will need to be careful! This will cause your program to recur infinitely! You will need to determine how to calculate the gross pay without calling this function, since if you do call it recursively within itself, there is no condition from which it will return.
Your method takes two parameters -- double payRate and int hours, but you are only specifying a double when you call computePaycheck in your main method.
It's not clear what you intend to happen, but the mismatched parameters should let you know what is wrong with your program.
The first statement of your computePaycheck method calls computePaycheck with a single parameter (a double) whereas the computePaycheck takes 2 parameters (a double and an int). That is why your code fails to compile.
If you "fix" this by using double grossPay = computePaycheck(payRate, hours); instead, this will compile BUT you will get infinite recursion! Don't you simply want to do double grossPay = payRate*hours; ?
It's clear that you set 2 parameters but from the main class you are only calling just one parameter. You should find a way to call the 2 parameters at the same time.

Categories