determine the periodic loan payment - java

am not getting this program to display my instalments correctly can I please get some help thanks......
package Loops;
import java.util.Scanner;
/**
*
*
*/
public class program {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//variabled decleared
double rate;
double payment;
//input
System.out.print("Enter Loan Amount:");
double principal = input.nextDouble();
System.out.print("Enter Annual Interest:");
double interest = input.nextDouble();
System.out.print("Total payments per year:");//12=monthly,4= quartely,2=semi-annually and 1=annually
double period = input.nextDouble();
System.out.print("Enter Loan Length :");
int length = input.nextInt();
//proces
double n = period * length;
rate = interest / 100;
double monthly_rate = rate / period;
payment = principal * (principal * (monthly_rate * Math.pow((1 + monthly_rate), n)));
System.out.printf("Your Monthly sum is %.2f", payment);
}
}

principal = 50000; //Redacted. Eating my words.
period = 4;
length = 4;
n = 16;
rate = 0.085;
monthly_rate = 0.085 / 16 = 0.0053125;
payment = 50000 * 50000 * 0.0053125 * (1 + 0.0053125) ^ 16;
= 2.5x10^9 * 0.0053125 * 1.088;
= Something remainingly massive
Basically... your formula is wrong. Wouldn't you need to divide by the power quotient? Where is your source on that formula?
payment = principal * (rate + (rate / ( Math.pow(1 + rate, n) - 1) ) );
Source
Example:
payment = 50000*(0.085+(0.085/(1.085^16-1)))
= 5830.68

Try this for your formula:
//this is how much a monthly payment is
payment = (rate + (rate / ((Math.pow(1 + rate), n) -1)) * principal
This is based off one of the first google results for the formula. Please post the results and expected answer if it is wrong.
I'm pretty sure your formula is just off, as you stated above that there should be a denominator in the equation.
You can use r* Math.pow ((1+r),n) to calculate the numerator and part of the denominator

Related

Java, computing the following formula

I am trying the write the formula in the image using Java. However, I get the wrong output. This is what I am so far for the computation.
Assume Input is: Loan Amount = 50000 and Length = 3 year.
My output is currently "676.08" for 'Monthly Payment' and "25661.0" for "Total Interest Payment".
"Monthly payment" should be "1764.03" and "Total Interest Payment" should be "13505.05".
Code is:
//Program that displays the interest rate and monthly payment based on the loan amount and length of loan the user inputs.
import java.util.Scanner;
public class bankLoanSelection{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
//Declarations.
double interestRate;
final double n = 12;
//Generates an account number in the range of 1 to 1000.
int accountnumber = (int)(Math.random() * 1000)+1;
//User input
System.out.print("Enter Loan Amount: $");
double L = input.nextDouble();
System.out.print("Length of Loan (years): ");
double i = input.nextDouble();
//selection structure using if and if-else statements.
if (L <= 1000)
interestRate = .0825;
else if (L <= 5000)
interestRate = .0935;
else if (L <= 10000)
interestRate = .1045;
else interestRate = .1625;
//Computations.
double MonthlyPayment = L * (interestRate / n) * Math.pow(1 + interestRate / n, i * n) / Math.pow(1 + interestRate / n, i * n) - 1;
double TotalAmountOfLoan = MonthlyPayment * i * n;
double TotalInterest = L - TotalAmountOfLoan;
//Output.
System.out.println("Account Number: #" + accountnumber);
System.out.println("Loan Amount: $" + L);
System.out.println("Loan Length (years): " + i);
System.out.println("Interest Rate: " + interestRate * 100 + "%");
System.out.printf("Total Monthly Payment: $%.2f%n", MonthlyPayment); //Rounds second decimal
System.out.println("Total Interest Payments: $" + TotalInterest);
}
}
You have to put round parentheses between condition.
It should be:
double MonthlyPayment = L * ((interestRate / n) * Math.pow(1 + interestRate / n, i * n))
/ (Math.pow(1 + interestRate / n, i * n) - 1);
You need to correct the arrangement of brackets in the denominator, the correct formula would be:
double numerator = L * (interestRate / n) * Math.pow(1 + interestRate / n, i * n)
double denominator = Math.pow(1 + interestRate / n, i * n) - 1;
double MonthlyPayment = numerator / denominator;
Try to break the problem into smaller units to solve.

Interest Calculator

Problem with my code for calculator - output values not correct
Here is my code, any response would be appreciated.
import java.util.Scanner;
public class Savings {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
//ask for initial amount
System.out.print("What is the initial savings amount? ");
double initialAmount = console.nextDouble();
// ask for number of months
System.out.print("What is the number of months to save? ");
int months = console.nextInt();
//ask for interest rate
System.out.print("What is the annual interest rate? ");
double interestRate = console.nextDouble();
//calculate total
double monthlyInterest = ((interestRate/100)*(1/12));
double number1 = (monthlyInterest + 1);
double number2 = Math.pow(number1, months);
double total = (initialAmount*number2);
System.out.println("$" + initialAmount + ", saved for " + months + " months at " + interestRate + "% will be valued at $" + total);
console.close();
}
}
final value ends up being the same value as initial
Change this:
double monthlyInterest = ((interestRate/100)*(1/12));
to
double monthlyInterest = (interestRate / 100) * (1.0 / 12.0);
You're trying to do integer division in floating-point context, so in monthlyInterest you are essentially multiplying interestRate / 100 with 0.
Add d with the numbers to convert them into double and keep the decimal value, this way -
double monthlyInterest = ((interestRate/100d)*(1/12d));
If you do 1/12 with integers, the output will be 0, but with 1/12d it will be 0.08333333333333333
Also, you can get rid of the extra parenthesis -
double monthlyInterest = (interestRate/100d)*(1/12d);
...
double number1 = monthlyInterest + 1;
...
double total = initialAmount * number2;

How to round to the nearest cent in Java

So I am writing a program that does some financial calculations. However, because I used double for my data types, the cents are not rounded. Here is the source code:
public class CentRoundingTest {
public static void main(String[] args) {
System.out.println("TextLab03, Student Version\n");
double principle = 259000;
double annualRate = 5.75;
double numYears = 30;
// Calculates the number of total months in the 30 years which is the
// number of monthly payments.
double numMonths = numYears * 12;
// Calculates the monthly interest based on the annual interest.
double monthlyInterest = 5.75 / 100 / 12;
// Calculates the monthly payment.
double monthlyPayment = (((monthlyInterest * Math.pow(
(1 + monthlyInterest), numMonths)) / (Math.pow(
(1 + monthlyInterest), numMonths) - 1)))
* principle;
// calculates the total amount paid with interest for the 30 year time.
// period.
double totalPayment = monthlyPayment * numMonths;
// Calculates the total interest that will accrue on the principle in 30
// years.
double totalInterest = monthlyPayment * numMonths - principle;
System.out.println("Principle: $" + principle);
System.out.println("Annual Rate: " + annualRate + "%");
System.out.println("Number of years: " + numYears);
System.out.println("Monthly Payment: $" + monthlyPayment);
System.out.println("Total Payments: $" + totalPayment);
System.out.println("Total Interest: $" + totalInterest);
}
}
My instructor also does not want this to use the DecimalFormat class. I was thinking to obtain the cents value by doing: variable-Math.floor(variable), and then rounding that amount to the nearest hundredth, then adding that together.
Without using the JDK-provided library classes that exist for this purpose (and would normally be used), the pseudocode for rounding arithmetically is:
multiply by 100, giving you cents
add (or subtract if the number is negative) 0.5, so the next step rounds to the nearest cent
cast to int, which truncates the decimal part
divide by 100d, giving you dollars)
Now go write some code.
Well, if you cannot use the DecimalFormat class, you could use printf():
TextLab03, Student Version
Principle : $259,000.00
Annual Rate : 5.75%
Number of years : 30.00
Monthly Payment : $1,511.45
Total Payments : $544,123.33
Total Interest : $285,123.33
public class CentRoundingTest {
public static void main(String[] args) {
System.out.println("TextLab03, Student Version\n");
double principle = 259000;
double annualRate = 5.75;
double numYears = 30;
// Calculates the number of total months in the 30 years which is the
// number of monthly payments.
double numMonths = numYears * 12;
// Calculates the monthly interest based on the annual interest.
double monthlyInterest = 5.75 / 100 / 12;
// Calculates the monthly payment.
double monthlyPayment = (((monthlyInterest * Math.pow(
(1 + monthlyInterest), numMonths)) / (Math.pow(
(1 + monthlyInterest), numMonths) - 1)))
* principle;
// calculates the total amount paid with interest for the 30 year time.
// period.
double totalPayment = monthlyPayment * numMonths;
// Calculates the total interest that will accrue on the principle in 30
// years.
double totalInterest = monthlyPayment * numMonths - principle;
printAmount("Principle", principle);
printPercent("Annual Rate", annualRate);
printCount("Number of years", numYears);
printAmount("Monthly Payment", monthlyPayment);
printAmount("Total Payments", totalPayment);
printAmount("Total Interest", totalInterest);
}
public static void printPercent(String label, double percentage) {
//System.out.printf("%-16s: %,.2f%%%n", label, percentage);
printNumber(label, percentage, "", "%", 16);
}
public static void printCount(String label, double count) {
//System.out.printf("%-16s: %,.2f%n", label, count);
printNumber(label, count, "", "", 16);
}
public static void printAmount(String label, double amount) {
//System.out.printf("%-16s: $%,.2f%n", label, amount);
printNumber(label, amount, "$", "", 16);
}
public static void printNumber(String label, double value, String prefix, String suffix, int labelWidth) {
String format = String.format("%%-%ds: %%s%%,.2f%%s%%n", labelWidth);
System.out.printf(format, label, prefix, value, suffix);
}
}

Java Currency Converter (How to convert int to Double + Many other issues)

I'm struggling with finding the remainders when converting the currency and then dividing it into dollar amounts. Also, creating a minimum amount of currency to be converted is causing me an issue. I understand alot of my code is a mess but this is my first Java project. Any help would be much appreciated.
/* Currency Conversion
*/
import java.util.Scanner;//to get keyboard input from user
public class Currency {
/**
* Converts from a foreign currency to US Dollars. Takes a
* deduction for the transaction fee. Displays how many of
* each bill and coin denomination the user receives.
*
* #param args no parameters expected
*/
public static void main(String[] args)
{
final double SEK_CONVERSION_RATE = .14;
/*
* You'll need a variable or constant for the transaction fee.
* (3% is fairly typical.) You'll also need a variable or
* constant for the minimum transaction fee.
*/
double transactionFee = .03;
final double MIN_TRANSACTION_FEE = 10.00;
/*
* You're going to need a variable for the amount of that
* currency the user wants to convert.
*/
//Before you can ask the user for input, you need a Scanner so you can read
//that input:
Scanner keyboard = new Scanner(System.in);
/*
* Now you're ready to interact with the user. You'll want
* to greet them and let them know what currency they can convert
* and what the rate of exchange is.
*/
System.out.print("Hello there, welcome to your one and only stop for Swedish Krona conversions. The exchange rate currently sits at .14" );
/*
* You should also let them know about the transaction fee.
*/
System.out.println(" The minimum transaction fee is $10.00 USD.");
/*
* Now you're ready to prompt the user for how much money they
* want to convert.
*/
System.out.println("How many Swedish Krona would you like to convert to US Dollar?");
double userCurrencyInput = keyboard.nextDouble();
/*
* And then use the Scanner to read in that input and initialize your
* variable for currency:
*/
double calculatedCurrInput = (userCurrencyInput*SEK_CONVERSION_RATE);
/* setting up casting to use later in program */
int calculatedCurrInputInt = (int) (calculatedCurrInput);
/*
* You've received an amount in a foreign currency, but you're going
* to need the amount in dollars. Furthermore, you're going to need
* to know the number of 20's, 10's,5's, 1's, quarters, dimes, nickels
* and pennies. And you're going to need to know the transaction fee.
* These should all be stored in variables.
*/
double totalTransaction = (userCurrencyInput*transactionFee + calculatedCurrInput);
int totalTransactionInt = (int) (totalTransaction);
/*Need to define the remainder correct to make change*/
System.out.println("The conversion is " + calculatedCurrInput);
int twentyDollar = 20;
int twentyDollarBills = calculatedCurrInputInt/twentyDollar;
int remainderOfTwenty = calculatedCurrInputInt%twentyDollar;
int tenDollar = 10;
int tenDollarBills = remainderOfTwenty/tenDollar;
int remainderOfTen = remainderOfTwenty%tenDollar;
int fiveDollar = 5;
int fiveDollarBills = remainderOfTen/fiveDollar;
int remainderOfFive = remainderOfTen%fiveDollar;
int oneDollar = 1;
int oneDollarBills = remainderOfFive/oneDollar;
int remainderOfOnes = remainderOfFive%oneDollar;
double remainderOfOnesDBL = (double) remainderOfOnes;
double quarter = .25;
double numberOfQuarters = remainderOfOnesDBL/quarter;
double remainderOfQuarters = remainderOfOnesDBL%quarter;
double dimes = .10;
double numberOfDimes = remainderOfQuarters/dimes;
double remainderOfDimes = remainderOfQuarters%dimes;
double nickels = .05;
double numberOfNickels = remainderOfDimes/nickels;
double remainderOfNickels = remainderOfDimes%nickels;
double pennies = .01;
double numberOfPennies = remainderOfNickels/pennies;
/*
* Now you're ready to calculate the amount in USD.
*/
/*
* Determine what the transaction fee would be, based on the
* percentage.
*/
double totalTransactionFee = (userCurrencyInput*transactionFee);
System.out.println("The transcation fee for your currency exchange would be $" + totalTransactionFee + " US.");
/*
* If the transaction fee is less than the minimum transaction
* fee, you'll need to charge the minimum transaction fee.
* (Hint, the Math class has min and max methods that receive
* two numbers and return either the smaller or larger of those
* two numbers.)
*/
/*
* You'll need to deduct the transaction fee from the total.
*/
/*
* Calculate the number of $20's they'll receive
*/
/*
* How much is left?
*/
/*
* Next do the same for $10's, $5's, etc.
*/
/*
* Finally, let the user know how many dollars their foreign currency
* converted to, what was deducted for the transaction fee, and how
* many of each denomination they are receiving.
*/
System.out.println("The amount of 20's is " +twentyDollarBills);
System.out.println("The amount of 10's is " +tenDollarBills);
System.out.println("The amount of 5's is " +fiveDollarBills);
System.out.println("The amount of 1's is " +oneDollarBills);
System.out.println("The amount of quarters is " +numberOfQuarters);
System.out.println("The amount of dimes is " +numberOfDimes);
System.out.println("The amount of nickels is " +numberOfNickels);
System.out.println("The amount of pennies is " +numberOfPennies);
}//end main
}//end Currency
Firstly, you shouldn't be converting from doubles to ints, as you will lose the amount after the decimal point. e.g.
double num = 1.9;
int number = (int) num;
System.out.println(number);
will print
1
Also, if you do
System.out.println(num % 1);
you get
0.8999999999999999 // not quite 0.9, which is what you were expecting
As #Laf pointed out, use BigDecimal instead.
BigDecimal SEK_CONVERSION_RATE = new BigDecimal(".14");
String userInput = keyboard.nextLine();
// Better precision constructing from a String
BigDecimal userCurrencyInput = new BigDecimal(userInput);
BigDecimal calculatedCurrInput = userCurrencyInput.multiply(SEK_CONVERSTION_RATE);
Hopefully you can work out the rest from there.
Hint: BigDecimal has a method divideAndRemainder() which returns a BigDecimal[], where the first part is the quotient, and the second part is the remainder.
http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#divideAndRemainder%28java.math.BigDecimal%29

More Than One Java Input

I am sort of a Newbie to this forum and to Java. I am having a difficult time trying to find a way to ask the user to enter more than one loan to compare from steps D down. I need to be able to ask the user for a different interest rate and number of years for the amount they entered in step A. So if they entered 10 then I would have to ask them 10 times for an interest rate and years and output it in a table format using tabs. Any help is much appreciated. Thanks in advance.
Edit: Thank you so much for your help! I updated the code.
//A. Enter the Number Of Loans to compare
String numberOfLoansString = JOptionPane.showInputDialog("Enter the amount of loans to compare:");
//Convert numberOfLoansString to int
int numberOfLoans = Integer.parseInt(numberOfLoansString);
//B. Enter the Amount/Selling Price of Home
String loanAmountString = JOptionPane.showInputDialog("Enter the loan amount:");
//Convert loanAmountString to double
double loanAmount = Double.parseDouble(loanAmountString);
//C. Enter the Down Payment on the Home
String downPaymentString = JOptionPane.showInputDialog("Enter the down payment on the Home:");
double downPayment = Double.parseDouble(downPaymentString);
//D. Ask the following for as many number of loans they wish to compare
//D1 Get the interest rate
double[] anualInterestRatesArray = new double[numberOfLoans];
double[] monthlyInterestRateArray = new double[numberOfLoans];
int[] numberOfYearsArray = new int[numberOfLoans];
double[] monthlyPaymentArray = new double[numberOfLoans];
double[] totalPaymentArray = new double[numberOfLoans];
for (int i=0; i < numberOfLoans; i++)
{
String annualInterestRateString = JOptionPane.showInputDialog("Enter the interest rate:");
double annualInterestRate = Double.parseDouble(annualInterestRateString);
anualInterestRatesArray[i] = (annualInterestRate);
//Obtain monthly interest rate
double monthlyInterestRate = annualInterestRate / 1200;
monthlyInterestRateArray[i] = (monthlyInterestRate);
//D2 Get the number of years
String numberOfYearsString = JOptionPane.showInputDialog("Enter the number of years:");
int numberOfYears = Integer.parseInt(numberOfYearsString);
numberOfYearsArray[i] = (numberOfYears);
//Calculate monthly payment
double monthlyPayment = loanAmount * monthlyInterestRate / (1 - 1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12));
//Format to keep monthlyPayment two digits after the decimal point
monthlyPayment = (int)(monthlyPayment * 100) / 100.0;
//Store monthlyPayment values in an array
monthlyPaymentArray[i] = (monthlyPayment);
//Calculate total Payment
double totalPayment = monthlyPaymentArray[i] * numberOfYears * 12;
//Format to keep totalPayment two digits after the decimal point
totalPayment = (int)(totalPayment * 100) / 100.0;
totalPaymentArray[i] = (totalPayment);
}
You need to do all the repeated processing logic inside a loop such as for( ... ) loop. Use an array to store different values for the number of loans.
Use for loops for this.
P.S : You can use other loops [while, do-while] as well.
An example for using for loop
int numberOfLoans = Integer.parseInt(numberOfLoansString);
//section of code which shouldnt be repeated here outside the loop.
for( int i = 0; i < numberOfLoans ; i++ )
{
//Write Step D here , because you want it to be repeated
}
You probably need to use arrays and loops. Use arrays to store all the values entered and a loop to get the values.
double[] anualInterestRates = new double[numberOfLoans];
double[] monthlyInterestRates = new double[numberOfLoans];
int[] numberOfyears = new int[numberOfLoans];
Then you can loop and ask for each loan values:
for(int i= 0; i < numberOfLoans; i++){
//get the anual interest rate
anualInterestRates[i] = the anual interets rate gotten
//etc
}
Now you have 3 arrays of values. You can use a second loop to calculate the output and display.

Categories

Resources