Java Computing Monthly Payments Loops - java

I have a question for yall, I am using loops for the following program and I cant understand how to make it so it displays each payment per month,
You are going to write a program which will display the payment schedule for a loan given an interest rate and the number of payments.
Prompt the user for a loan amount, the annual interest rate, number of years to pay off the loan. First, you will calculate the monthly payment using a formula below. Then you will write a loop displaying the monthly payment breakdown: interest amount, principal applied to the loan, and the balance of the loan.
For a 1 year loan (12 monthly payments) for $10,000 at 7%, the payment breakdown looks like the following:
monthly payment = 865.27
payment:1 interest: 58.33 principal: 806.93 balance: 9193.07
HERE IS THE ISSUE ABOVE I CANT GET IT TO DISPLAY THE AMOUNT OF PAYMENTS FOR (x) MONTHS AND FOR IT TO DISPLAY THE REST OF THE INFO WITH IT.
import java.text.NumberFormat;
import java.util.Scanner;
public class MothlyPay {
public static double calculateMonthlyPayment(
int loanAmount, int termInYears, double interestRate) {
// Convert interest rate into a decimal
// eg. 6.5% = 0.065
interestRate /= 100.0;
// Monthly interest rate
// is the yearly rate divided by 12
double monthlyRate = interestRate / 12.0;
// The length of the term in months
// is the number of years times 12
int termInMonths = termInYears * 12;
// Calculate the monthly payment
// Typically this formula is provided so
// we won't go into the details
// The Math.pow() method is used calculate values raised to a power
double monthlyPayment =
(loanAmount*monthlyRate) /
(1-Math.pow(1+monthlyRate, -termInMonths));
return monthlyPayment;
}
public static void main(String[] args) {
// Scanner is a great class for getting
// console input from the user
Scanner scanner = new Scanner(System.in);
// Prompt user for details of loan
System.out.print("Enter loan amount: ");
int loanAmount = scanner.nextInt();
System.out.print("Enter loan term (in years): ");
int termInYears = scanner.nextInt();
System.out.print("Enter interest rate: ");
double interestRate = scanner.nextDouble();
// Display details of loan
double monthlyPayment = calculateMonthlyPayment(loanAmount, termInYears, interestRate);
double totalPayed = 0;
int month = 1;
double loanAmountRemaining;
// NumberFormat is useful for formatting numbers
// In our case we'll use it for
// formatting currency and percentage values
while(totalPayed <= loanAmount){
totalPayed = totalPayed + monthlyPayment;
double totalLoanAmount = loanAmount + interestRate;
loanAmountRemaining = totalLoanAmount - totalPayed;
month ++;
}
if(monthlyPayment > loanAmount)
totalPayed = totalPayed + loanAmountRemaining;
}
// Display details of the loan
//HERE IS THE ISSUE BELOW, I CANT GET IT TO DISPLAY THE AMOUNT OF PAYMENTS FOR (x) MONTHS AND FOR IT TO DISPLAY THE REST OF THE INFO WITH IT FOR THE FOLLOWING VARIABLE LISTED IN THE PRINTF STATEMENT.
System.out.printf("%9s %9s %9s %9s\n", "monthlypayment", "interestRate", "loanAmount", "loanAmountRemaining");
}
//When user put in the loan amount, interest rate, months, It needs display like the picture below.

Right now, you don't have your print statement in any specific method, meaning it won't be called. I would recommend putting it in your main method, and then running a loop to find and print your values.

Related

How to use System.out.printf() to display output of number to only two decimal places?

I am creating my first java program for the class. The purpose of the program is to calculate interest for deposit for year one and year two. My issue comes when the code outputs the final totals. The last two lines are supposed to use System.out.printf(). I keep getting the error Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = 'i'. How do I correct this?
public static void main(String... args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Hello World!");
//declares variables
double interest = 0;
double balance = 0;
double deposit = 0;
double secondYearBalance = 0;
double secondYearInterest = 0;
//displays welcome message
System.out.println("Welcome to George's Interest Calculator");
//prompts user for input
System.out.println("Please enter your initial deposit:");
deposit = keyboard.nextInt();
//Finds outs interest interest earned on deposit
interest = deposit * TAXRATE;
//Finds out the amount of the balance
balance = deposit + interest;
//finds out second year balance
secondYearInterest = balance * TAXRATE;
secondYearBalance = secondYearInterest + balance;
//Outputs totals
System.out.printf("Your balance after one year with a 4.9% interest rate is $%7.2f %n", balance);
System.out.printf("Your balance after two years with a 4.9% interest rate is $%7.2f %n", secondYearBalance);
System.out.println();
}
The % symbol is used in a printf string for 'put a variable here'.
That's problematic when you write 4.9% interest rate because java thinks that % i is you saying: "a variable goes here". The fix is trivial; a double % is how you write a single percent. Thus:
System.out.printf("Your balance after one year with a 4.9%% interest rate is $%7.2f %n", balance);

How to implement a particular maths formula in Java?

package methods;
import java.util.Scanner;
/**
*
* #author Billy
*/
public class Methods {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
double Loanamount; // Loan amount from user
double Aintrate; // User's annual interest rate
double months; // Number of months on loan
double monp; // Monthly payment
double Mintrate; // Monthly interest rate
double n; // The number of payments
// declare an instance of Scanner to read the datastream from the keyboard.
Scanner kb = new Scanner(System.in);
// Get user's loan amount
System.out.print("Please enter your total loan amount: ");
Loanamount = kb.nextDouble();
// Get user's interest rate
System.out.print("Please enter your annual interest rate as a decimal: ");
Aintrate = kb.nextDouble();
// Get user's number of months
System.out.print("Please enter the number of months left on your loan: ");
months = kb.nextDouble();
// Calculate montly interest rate
Mintrate = ((Aintrate / 12));
System.out.println("Your monthly interest rate is " + " " + Mintrate);
// Calculate number of payments
n = ((months * 12));
// Calculate monthly payment
My next job is to find out the monthly payment using this formula.
M = P [ i(1 + i)^n ] / [ (1 + i)^n – 1]
Where
M = monthly mortgage payment
P = The amount borrowed (Loanamount)
i = Monthly interest rate (Mintrate)
n = the number of payments
I tried the following but I just cant figure it out
monp = Loanamount [Mintrate(1+ Mintrate)^n] / [(1+ Mintrate)^n-1 ];
You need to use Math.pow effectivley here.
Try using following in your code
monp = Loanamount*(Mintrate*Math.pow((1+ Mintrate),n)) / (Math.pow((1+ Mintrate),n-1 ) ;
Math.pow is what you need instead of ^. Also you can't use [ or ]. You have to use parenthesis ( and ).
More math functions can be found at:
http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html
The method for ^ is called Math.pow(double a, double b); in Java.
Where a is the number to be raised b times.
Your formula would then look like monp = Loanamount Math.pow((Mintrate(1+ Mintrate), n)) / (Math.pow((1+ Mintrate), n-1));
Reference
You need to call Math.pow(double,double)
OR you could import the required class as..
import static java.lang.Math.pow;
and then use pow() function

Where do I input values?

Java Gurus,
Working on a class assignment and we are given a set of two programs. One calls on another to calculate interest rate, balances, etc for a bank account. What I am having problems with, is figuring out where I am supposed to input the variables we are given to get a successful compile for our program. Below are the two Java files we were given. I made the adjustments to correct all the purposeful errors in the code so everything compiles nicely so far.
public class BankAccount {
private double balance; // Account balance
private double interestRate; // Interest rate
private double interest; // Interest earned
/**
* The constructor initializes the balance
* and interestRate fields with the values
* passed to startBalance and intRate. The
* interest field is assigned to 0.0.
*/
public BankAccount(double startBalance, double intRate) {
balance = startBalance;
interestRate = intRate;
interest = 0.0;
}
/**
* The deposit method adds the parameter
* amount to the balance field.
*/
public void deposit(double amount) {
balance += amount;
}
/**
* The withdraw method subtracts the
* parameter amount from the balance
* field.
*/
public void withdraw(double amount) {
balance -= amount;
}
/**
* The addInterest method adds the interest
* for the month to the balance field.
*/
public void addInterest() {
interest = balance * interestRate;
balance += interest;
}
/**
* The getBalance method returns the
* value in the balance field.
*/
public double getBalance() {
return balance;
}
/**
* The getInterest method returns the
* value in the interest field.
*/
public double getInterest() {
return interest;
}
}
Here is the Program2.java which is what we need to compile:
import java.text.DecimalFormat; // Needed for 2 decimal place amounts
import java.util.Scanner; // Needed for the Scanner class
public class Program2 {
public static void main(String[] args) {
BankAccount account; // To reference a BankAccount object
double balance, // The account's starting balance
interestRate, // The annual interest rate
pay, // The user's pay
cashNeeded; // The amount of cash to withdraw
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Create an object for dollars and cents
DecimalFormat formatter = new DecimalFormat("#0.00");
// Get the starting balance.
System.out.print("What is your account's " + "starting balance? ");
balance = keyboard.nextDouble();
// Get the monthly interest rate.
System.out.print("What is your monthly interest rate? ");
interestRate = keyboard.nextDouble();
// Create a BankAccount object.
account = new BankAccount(balance, interestRate);
// Get the amount of pay for the month.
System.out.print("How much were you paid this month? ");
pay = keyboard.nextDouble();
// Deposit the user's pay into the account.
System.out.println("We will deposit your pay " + "into your account.");
account.deposit(pay);
System.out.println("Your current balance is %bodyquot; + formatter.format( account.getBalance() )");
// Withdraw some cash from the account.
System.out.print("How much would you like " + "to withdraw? ");
cashNeeded = keyboard.nextDouble();
account.withdraw(cashNeeded);
// Add the monthly interest to the account.
account.addInterest();
// Display the interest earned and the balance.
System.out.println("This month you have earned %bodyquot; + formatter.format( account.getInterest() )" +
" in interest.");
System.out.println("Now your balance is %bodyquot; + formatter.format( account.getBalance() ) )");
}
}
What I am required to enter is 500 for Starting Balance, 0.00125 for Monthly Interest Rate (Interest is compounded monthly in the code and pretty sure I know where to put this variable), 1000 Monthly Pay and 900 withdrawl amount. The end result should be $600.75.
Is all of my code there or do I need to declare the value of the variables Starting Balance, Interest Rate, Monthly Pay and Withdrawl Amount?
Please let me know if I am doing something wrong, or if the answer is smack in front of my face and I am just blind today.
Its a copy paste issue in your code.
Change From:
System.out.println("Your current balance is %bodyquot; + formatter.format( account.getBalance() )");
To:
System.out.println("Your current balance is " + formatter.format( account.getBalance() ));
Use below mentioned updated code.
import java.text.DecimalFormat; // Needed for 2 decimal place amounts
import java.util.Scanner; // Needed for the Scanner class
public class Program2 {
public static void main(String[] args) {
BankAccount account; // To reference a BankAccount object
double balance, // The account's starting balance
interestRate, // The annual interest rate
pay, // The user's pay
cashNeeded; // The amount of cash to withdraw
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Create an object for dollars and cents
DecimalFormat formatter = new DecimalFormat("#0.00");
// Get the starting balance.
System.out.print("What is your account's " + "starting balance? ");
balance = keyboard.nextDouble();
// Get the monthly interest rate.
System.out.print("What is your monthly interest rate? ");
interestRate = keyboard.nextDouble();
// Create a BankAccount object.
account = new BankAccount(balance, interestRate);
// Get the amount of pay for the month.
System.out.print("How much were you paid this month? ");
pay = keyboard.nextDouble();
// Deposit the user's pay into the account.
System.out.println("We will deposit your pay into your account.");
account.deposit(pay);
System.out.println("Your current balance is " + formatter.format( account.getBalance() ));
// Withdraw some cash from the account.
System.out.print("How much would you like to withdraw? ");
cashNeeded = keyboard.nextDouble();
account.withdraw(cashNeeded);
// Add the monthly interest to the account.
account.addInterest();
// Display the interest earned and the balance.
System.out.println("This month you have earned " + formatter.format( account.getInterest() ) +
" in interest.");
System.out.println("Now your balance is " + formatter.format( account.getBalance() ) );
}
}
You're going to want to input those values either when you create your BankAccount class in your second program or at runtime. You could try something like this:
BankAccount account = new BankAccount(500, 0.00125)
And then input the rest of the values at runtime, or you could create local variables in Program 2 for everything and then create a new BankAccount using them as parameters.
Hope it helps.

(Java Beginner) - Having trouble with a program

Ok so I am working on a program that involves loans and gives information to the user about loans from what the user inputs.
The purpose of this program I am writing is for the user to be asked to input a loan amount and the number of years that they have to pay it off. Once the user has given this information, the program will take the loan amount and number of years and tell the user the annual interest rate, monthly payment and the total amount.
ALSO, if the user enters a loan amount of -1, the program is supposed to terminate.
Below is my code thus far:
package Loans;
import java.util.Scanner;
public class Loans {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
double monthlyInterestRate;
double annualInterestRate;
double monthlyPayment;
double total;
double numberOfYears;
double loanAmount;
System.out.println("This program will compute the monthly payments and total payments for a loan amount on interest rates starting at 5%, incrementing by 1/8th percent up to 8%.");
//Formula to Calculate Monthly Interest Rate:
monthlyInterestRate = (annualInterestRate/1200);
//Formula to Calculate Monthly Payment:
monthlyPayment = (loanAmount*monthlyInterestRate);
//Formula To Calculate Annual Interest Rate:
annualInterestRate = (1-(Math.pow(1/(1 + monthlyInterestRate), numberOfYears * 12)));
//Formula To Calculate The Total Payment:
total = (monthlyPayment*numberOfYears*12);
while(true)
{
System.out.println("Please enter in the loan amount.");
double loanAmount = input.nextDouble();
System.out.println("Please enter in the number of years.");
double numberOfYears = input.nextDouble();
System.out.println("Interest Rate: " + annualInterestRate);
System.out.println("Monthly Payment: " + monthlyPayment);
System.out.println("Total Payment: " + total);
}
}
}
This does not compile and I'm not sure why. (Again, I'm a beginner)
The errors I am receiving are on the line that reads "double loanAmount = input.nextDouble();" AND the line that reads "double numberOfYears = input.nextDouble();".
The error for the first line says, "Duplicate local variable loanAmount".
The error for the second line says, "Multiple markers at this line
- Line breakpoint:Loans [line: 39] -
main(String[])
- Duplicate local variable numberOfYears"
Any feedback is appreciated.
The error you get is pretty much self explanatory. You have defined both "loanAmount" and "numberOfYears" two times in main. Either rename them or declare them only once.
If you are a beginner in coding I would recommend you use an IDE like Eclipse or Netbeans. They will point out compilation errors along with suggestions on how to fix them.
Easy enough to fix. So the issue is that in this segment:
System.out.println("Please enter in the loan amount.");
double loanAmount = input.nextDouble();
System.out.println("Please enter in the number of years.");
double numberOfYears = input.nextDouble();
You are re-defining your double variables loanAmount and numberOfYears, which is going to cause an error. Take out the "double" in both lines where they are used.
The other change you need to make is to intialize these variables at the top of your code. Change the lines where you initialize all of your double variables and set them equal to 0, for example:
double annualInterestRate = 0;
double numberOfYears = 0;
double loanAmount = 0;
When a variable has a call in a program, it must first be initialized. It doesn't matter what it's initialized to, since its end value will be determined by the program's actions, but it absolutely needs to be initialized at some point.
I made exactly these changes and the program compiled successfully.
Hope this helps!

loan calculator that implements multiple methods

I have been working on a program that is a Java loan payment calculator for my comp sci class. The programs requriements are:
ask user for loan amount, annual interest rate, and number of months
call a method to calculate and return the monthly interest rate
call a method to calculate and return the monthly payments
call a method to print a loan statement showing the amount borrowed, annual interest rate, the number of months and the monthly payment.
This is my first time working with multiple methods. I have developed the code so far as shown below. The netbeans editor is not giving me any errors, however, it does not print the statements from my last method. My questions are:
are my methods set up correctly and passing parameters correctly
why won't the statements print at the end
am i capturing my other methods correctly? Do i need to enter variables in the main method and then call them in the final method.
is any of my code redundant?
I am not really sure how to proceed from here.
public class CarLoan {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// declare variables for main method
double loanAmount;//double value loan amount
double annualInterestRate;//double value interest rate
int numberOfMonths;//int value for number of months
double monthlyPayment;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the amount of your loan.");
loanAmount = keyboard.nextDouble();
System.out.println("Please enter the annual interest rate as a decimal. Ex. 7.5% = .075");
annualInterestRate = keyboard.nextDouble();
System.out.println("Please enter the number of months you have to pay back your loan.");
numberOfMonths = keyboard.nextInt();
}
*************************************************
public static double calcMonthlyInterestRate(double annualInterestRate){
double monthlyInterestRate;
monthlyInterestRate = (annualInterestRate/12);
return monthlyInterestRate;
}//end method CalcMonthlyInterestRate
**************************************************************************************
public static double calcMonthlyPayment(double monthlyInterestRate, double loanAmount, int numberOfMonths ){
double monthlyPayment;
double calcMonthlyPayment;
calcMonthlyPayment = (monthlyInterestRate*loanAmount)/(1-(1+monthlyInterestRate)-numberOfMonths);
return monthlyPayment = calcMonthlyPayment;
}//end method CalcMonthlyPayment
****************************************************************************************
public static void loanStatment (double loanAmount, double annualInterestRate, intnumberOfMonths, double monthlyPayment){
System.out.println("Your loan amount is " +loanAmount);
System.out.println(annualInterestRate);
System.out.println(numberOfMonths);
System.out.println(monthlyPayment);
}
}//end main method
}//end main method
Have a look at your main method and you will see that all you are doing is declaring your variables and receiving input. Your other methods that perform the calculations and the loanStatment (sic) method that prints your results are never called.
I would recommend you read up on the basics as you will waste less of your time with very simple errors like this one.
You need to change your main method like shown below.
import java.util.Scanner;
public class CarLoan {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// declare variables for main method
double loanAmount;//double value loan amount
double annualInterestRate;//double value interest rate
int numberOfMonths;//int value for number of months
double monthlyPayment;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the amount of your loan.");
loanAmount = keyboard.nextDouble();
System.out.println("Please enter the annual interest rate as a decimal. Ex. 7.5% = .075");
annualInterestRate = keyboard.nextDouble();
System.out.println("Please enter the number of months you have to pay back your loan.");
numberOfMonths = keyboard.nextInt();
System.out.println("Please enter your monthly payment.");
monthlyPayment = keyboard.nextDouble();
System.out.println("Your monthly interest rate is ");
System.out.println(calcMonthlyInterestRate(annualInterestRate));
System.out.println("Your monthly payment is ");
System.out.println(calcMonthlyPayment(calcMonthlyInterestRate(annualInterestRate),loanAmount,numberOfMonths));
loanStatment(loanAmount,annualInterestRate,numberOfMonths,monthlyPayment);
}
public static double calcMonthlyInterestRate(double annualInterestRate){
double monthlyInterestRate;
monthlyInterestRate = (annualInterestRate/12);
return monthlyInterestRate;
}//end method CalcMonthlyInterestRate
public static double calcMonthlyPayment(double monthlyInterestRate, double loanAmount, int numberOfMonths ){
double monthlyPayment;
double calcMonthlyPayment;
calcMonthlyPayment = (monthlyInterestRate*loanAmount)/(1-(1+monthlyInterestRate)-numberOfMonths);
return monthlyPayment = calcMonthlyPayment;
}//end method CalcMonthlyPayment
public static void loanStatment (double loanAmount,
double annualInterestRate,
int numberOfMonths,
double monthlyPayment){
System.out.println("Your loan amount is " +loanAmount);
System.out.println(annualInterestRate);
System.out.println(numberOfMonths);
System.out.println(monthlyPayment);
}
}//end of CarLoan
I would really suggest you read up a little on how main method works in Java.That will be helpful.

Categories