For loop increments array backwards - java

I am trying to do some calculations using different values stored in an array. The problem is that my array's values increase but the calculations are coming out decreasing.
Main:
public static void main(String[] args) {
double pay, rate, deposit;
int years;
char yes = 'y';
char answer;
double[] interest = new double[15];
interest[0] = 3.75;
interest[1] = 4.00;
interest[2] = 4.25;
interest[3] = 4.50;
interest[4] = 4.75;
interest[5] = 5.00;
interest[6] = 5.25;
interest[7] = 5.50;
interest[8] = 5.75;
interest[9] = 6.00;
interest[10] = 6.25;
interest[11] = 6.50;
interest[12] = 6.75;
interest[13] = 7.00;
interest[14] = 7.25;
mortgageClass mortgagePayment = new mortgageClass();
Scanner keyboard = new Scanner(System.in);
System.out.print("Are you a first time buyer? ");
answer = keyboard.next().charAt(0);
if (answer == yes)
{
mortgagePayment.setRate(4.50);
}
else
{
mortgagePayment.setRate(interest[0]);
}
System.out.print("What is your mortage term? ");
years = keyboard.nextInt();
mortgagePayment.setTermYears(years);
System.out.print("What is your amount of mortgage? ");
pay = keyboard.nextDouble();
mortgagePayment.setAmount(pay);
System.out.print("What is your deposit amount? ");
deposit = keyboard.nextDouble();
mortgagePayment.setdepositAmt(deposit);
System.out.printf("Your mortgage payment is %.2f ", mortgagePayment.getMonthlyPayment());
System.out.println();
for ( int i = 0; i < interest.length; i++ ){
mortgagePayment.setRate(interest[i]);
System.out.printf("Your mortgage payment is %.2f ", mortgagePayment.getMonthlyPayment());
System.out.println();
}
}
MortgagePayment Class
public class mortgageClass {
private double rate;
private double loanAmount;
private double depositAmt;
private int termYears;
public void setRate(double r) {
rate = r;
}
public void setAmount(double loan) {
loanAmount = loan;
}
public void setTermYears(int years) {
termYears = years;
}
public void setdepositAmt(double amount) {
depositAmt = amount;
}
public double getMonthlyPayment() {
rate /= 100.0;
loanAmount = loanAmount - depositAmt;
double monthlyRate = rate / 12.0;
int termMonths = termYears * 12;
double monthlyPayment = (loanAmount * monthlyRate)
/ (1 - Math.pow(1 + monthlyRate, -termMonths));
return monthlyPayment;
}
}
The output is decreasing
Your mortgage payment is 1309.00
Your mortgage payment is 1220.49 //my output
Your mortgage payment is 1128.42
When it should be increasing
Your mortgage payment is 1309.00
Your mortgage payment is 1331.44 //Expected output
Your mortgage payment is 1354.10
Obviously the first value is assigned correctly, so why isn't the increment working?
EDIT: I have added a print statement to see if the correct values are being used and it seems like they are
for ( int i = 0; i < interest.length; i++ ){
mortgagePayment.setRate(interest[i]);
//System.out.printf("Your mortgage payment is %.2f ", mortgagePayment.getMonthlyPayment());
System.out.println(interest[i]);
System.out.printf("Your mortgage payment is %.2f ", mortgagePayment.getMonthlyPayment());
System.out.println();
Output:
3.75
Your mortgage payment is 1309.00
4.0
Your mortgage payment is 1220.49
4.25
Your mortgage payment is 1128.42
4.5
Your mortgage payment is 1032.74
..... I would just like to know WHY the calculations are decreasing.

skip
interest[i] = i + 1;
EDITED 2nd time :
the problem is
loanAmount = loanAmount - depositAmt;
every time you call mortgagePayment.getMonthlyPayment()
it decreasing the loanAmount , Thats why monthly amount is coming down
suggested change :
public double getloanAmount(){
return loanAmount - depositAmt;
}
public double getMonthlyPayment() {
rate /= 100.0;
double loanAmount = getloanAmount();
double monthlyRate = rate / 12.0;
int termMonths = termYears * 12;
double monthlyPayment = (loanAmount * monthlyRate) / (1 - Math.pow(1 + monthlyRate, -termMonths));
return monthlyPayment;
}
that will fix the problem.
EDITED :
use this fromula Monthly Mortgage Payment
M = P [ i(1 + i)^n ] / [ (1 + i)^n – 1]
The variables are as follows:
M = monthly mortgage payment
P = the principal, or the initial amount you borrowed.
i = your monthly interest rate. Your lender likely lists interest rates as an annual figure,
so you’ll have to divide by 12, for each month of the year. So, if your rate is 5%,
then the monthly rate will look like this: 0.05/12 = 0.004167.
n = the number of payments, or the payment period in months. If you take out a 30-year fixed rate mortgage,
this means: n = 30 years x 12 months per year = 360 payments.

Related

Access Method result in If statement

Is it possible to access the result of a method statement in an If statement? I'm writing a program to calculate a meter reading assignment. Netbeans states it cannot find the symbol of the methodName I created. Here is the code so far:
public class Meter_Utility {
//Begin Main Method
public static void main(String[] args) {
//new scanner object
Scanner input = new Scanner(System.in);//create new scanner object
//Declarations
double prevMeter;
double currMeter;
double rate = 0;
// double totalUsage = 0;
//obtain meter readings from user
System.out.print("Welcome to the City Power Bill Calculator! Please enter your previous meter reading: ");
prevMeter = input.nextDouble();
System.out.print("Please enter your Current meter reading: ");
currMeter = input.nextDouble();
//output total usage
System.out.printf("your usage was: %.1f KwHs", totalUsage(prevMeter, currMeter));
//calculate rate
if (totalUsage < 500) {
rate = .0809;
}
else if (totalUsage > 500 && totalUsage < 900){
rate = .091;
}
else {
rate = .091;
}
//output rate
System.out.printf("\nYour rate was: %.4f/KwH", rate);
} //End Main Method
/**
* Method to calculate total Usage
* #param u1
* #param u2
* #return difference of month 1 and month 2
*/
private static double totalUsage(double u1, double u2) {
return u2 - u1;
}
}
So I would like totalUsage to be accessible in the if statement, that way I can determine the rate and carry on.
I researched on stackoverflow already for a similar posts and came up empty. I researched here: for the if/else statements already as well:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
You should declare a variable to stock your total usage, or call the method each time.
With a variable :
double totalUsage = totalUsage(prevMeter, currMeter);
System.out.printf("your usage was: %.1f KwHs", totalUsage);
//calculate rate
if (totalUsage < 500.0) {
rate = .0809;
}
else if (totalUsage > 500.0 && totalUsage < 900.0){
rate = .091;
}
else {
rate = .091;
}
//output rate
System.out.printf("\nYour rate was: %.4f/KwH", rate);
By calling method :
//output total usage
System.out.printf("your usage was: %.1f KwHs", totalUsage(prevMeter, currMeter));
//calculate rate
if (totalUsage(prevMeter, currMeter) < 500.0) {
rate = .0809;
}
else if (totalUsage(prevMeter, currMeter) > 500.0 && totalUsage(prevMeter, currMeter) < 900.0){
rate = .091;
}
else {
rate = .091;
}
//output rate
System.out.printf("\nYour rate was: %.4f/KwH", rate);

Java Loan Amortization

Please what could be wrong with my code. it is an iteration approach to: The monthly payment for a given loan pays the principal and the interest. The monthly interest is computed by multiplying the monthly interest rate and the balance (the remaining principal).
The principal paid for the month is therefore the monthly payment minus the
monthly interest. Write a program that lets the user enter the loan amount, number of years, and interest rate and displays the amortization schedule for the loan.
However, i keep getting NaN just to calculate monthly payment.code is as follow:
import java.util.Scanner;
public class Amortization {
public static void main(String[] args) {
//create Scanner
Scanner s = new Scanner(System.in);
//prompt Users for input
System.out.print("Enter loan Amount:");
int loanAmount = s.nextInt();
System.out.print("Enter numberof Years:");
int numberYear =s.nextInt();
System.out.print("Enter Annual Interest Rate:");
int annualRate = s.nextInt();
double monthlyrate= annualRate/1200;
double monthlyPayment = loanAmount*monthlyrate/(1 -1/Math.pow(1+monthlyrate,numberYear*12));
System.out.printf("%6.3f",monthlyPayment);
// TODO code application logic here
}
}
I just wrote code for a similar problem. I share with you my solution.
I got a lot of ideas from http://java.worldbestlearningcenter.com/2013/04/amortization-program.html
public class LoanAmortizationSchedule {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Prompt the user for loan amount, number of years and annual interest rate
System.out.print("Loan Amount: ");
double loanAmount = sc.nextDouble();
System.out.print("Number of Years: ");
int numYears = sc.nextInt();
System.out.print("Annual Interest Rate (in %): ");
double annualInterestRate = sc.nextDouble();
System.out.println(); // Insert a new line
// Print the amortization schedule
printAmortizationSchedule(loanAmount, annualInterestRate, numYears);
}
/**
* Prints amortization schedule for all months.
* #param principal - the total amount of the loan
* #param annualInterestRate in percent
* #param numYears
*/
public static void printAmortizationSchedule(double principal, double annualInterestRate,
int numYears) {
double interestPaid, principalPaid, newBalance;
double monthlyInterestRate, monthlyPayment;
int month;
int numMonths = numYears * 12;
// Output monthly payment and total payment
monthlyInterestRate = annualInterestRate / 12;
monthlyPayment = monthlyPayment(principal, monthlyInterestRate, numYears);
System.out.format("Monthly Payment: %8.2f%n", monthlyPayment);
System.out.format("Total Payment: %8.2f%n", monthlyPayment * numYears * 12);
// Print the table header
printTableHeader();
for (month = 1; month <= numMonths; month++) {
// Compute amount paid and new balance for each payment period
interestPaid = principal * (monthlyInterestRate / 100);
principalPaid = monthlyPayment - interestPaid;
newBalance = principal - principalPaid;
// Output the data item
printScheduleItem(month, interestPaid, principalPaid, newBalance);
// Update the balance
principal = newBalance;
}
}
/**
* #param loanAmount
* #param monthlyInterestRate in percent
* #param numberOfYears
* #return the amount of the monthly payment of the loan
*/
static double monthlyPayment(double loanAmount, double monthlyInterestRate, int numberOfYears) {
monthlyInterestRate /= 100; // e.g. 5% => 0.05
return loanAmount * monthlyInterestRate /
( 1 - 1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12) );
}
/**
* Prints a table data of the amortization schedule as a table row.
*/
private static void printScheduleItem(int month, double interestPaid,
double principalPaid, double newBalance) {
System.out.format("%8d%10.2f%10.2f%12.2f\n",
month, interestPaid, principalPaid, newBalance);
}
/**
* Prints the table header for the amortization schedule.
*/
private static void printTableHeader() {
System.out.println("\nAmortization schedule");
for(int i = 0; i < 40; i++) { // Draw a line
System.out.print("-");
}
System.out.format("\n%8s%10s%10s%12s\n",
"Payment#", "Interest", "Principal", "Balance");
System.out.format("%8s%10s%10s%12s\n\n",
"", "paid", "paid", "");
}
}
That's because you are entered number followed by an enter . So your nextLine method call just reads return key while nextInt just reads integer value ignoring the return key. To avoid this issue:
Just after reading input, you call something like:
int loanAmount=s.nextInt();
s.nextLine();//to read the return key.
Also, it might be a good idea to format your code (identation)

How do I display how many months it took?

Heres my code:
import java.util.*;
public class LoanCalculator {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
//Declare variables
double loanAmount;
double interestRate;
double monthlyPayment;
double interest = 0;
double principal = 0;
int months;
System.out.print("Enter the amount of your loan: ");
loanAmount = console.nextDouble();
System.out.println();
System.out.print("Enter the interest rate per year: ");
interestRate = console.nextDouble();
System.out.println();
System.out.print("Enter your monthly payment amount: ");
monthlyPayment = console.nextDouble();
System.out.println();
interestRate = (interestRate / 12) /100;
for (months = 1; months <= loanAmount; months++)
{
interest = (loanAmount * interestRate);
principal = monthlyPayment - interest;
loanAmount = loanAmount - principal;
System.out.println(months);
}
}
}
I want the program to output how many months the loan took to pay off, but it's listing every month. How can I do this? Also if the monthly payment is less then the first month's interest then the loan amount will increase, how can I warn the user if this happens?
To output only how many months it took, move the System.out outside of the loop. To warn the user add a check before the loop
if (monthlyPayment < loanAmount * interestRate) {
System.out.println("your warning...");
}
for (months = 1; months <= loanAmount; months++) {
interest = (loanAmount * interestRate);
principal = monthlyPayment - interest;
loanAmount = loanAmount - principal;
}
System.out.println("Number of months: " + months);

Separate two loops in java

I should write a program that reads balance and interest rate, and displays the value of the account in ten years with anually, monthly and daily compounds.
I have written for yearly compounding and for monthly. In the second loop for monthly rate, program reads value of "balance" after compounding yearly, while I need it read primary value. How is it possible to separate two loops, so they do not influence each other? Here is my code:
import java.util.Scanner;
public class BankInterest {
public static void main(String []args) {
System.out.println("Please enter your balance: ");
Scanner keyboard = new Scanner(System.in);
double balance = keyboard.nextDouble();
int years = 0;
int months = 0;
int days = 0;
System.out.println("Please enter the ann1ual interest rate in decimal form: ");
double interestRate = keyboard.nextDouble();
while (years<10) {
double interest = balance * interestRate;
balance = balance + interest;
years++;
}
System.out.println("Balance after 10 years with annual interest is " + balance);
while (months<120) {
double interest = balance * interestRate/12;
balance = balance + interest;
months++;
}
System.out.println("Balance after 10 years with monthly interest rate is " + balance);
}
}
When program is run and I input 100 for balance and 0.02 to interest rate, yearly compounding works well and displays:
Balance after 10 years with annual interest is 121.89944199947573
And second loop takes this value as balance and displays:
Balance after 10 years with monthly interest rate is 148.86352955791543
While, if my code was right it should display this number: 122.119943386
You can place both loops in different functions and pass both balance and interesRate as arguments, like below.
import java.util.Scanner;
public class BankInterest {
static public double annualInterest(double balance, double interestRate) {
int years = 0;
while (years < 10) {
double interest = balance * interestRate;
balance = balance + interest;
years++;
}
return balance;
}
static public double monthlyInterest(double balance, double interestRate) {
int months = 0;
while (months < 120) {
double interest = balance * interestRate/12;
balance = balance + interest;
months++;
}
return balance;
}
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter your balance: ");
double balance = keyboard.nextDouble();
System.out.println("Please enter the ann1ual interest rate in decimal form: ");
double interestRate = keyboard.nextDouble();
System.out.println("Balance after 10 years with annual interest is " +
annualInterest(balance, interestRate));
System.out.println("Balance after 10 years with monthly interest rate is " +
monthlyInterest(balance, interestRate));
}
}
You need to declare two different variables for initial balance and updated balance so that you can access the original balance in both loops. I have shown this below.
public static void main(String []args) {
System.out.println("Please enter your balance: ");
Scanner keyboard = new Scanner(System.in);
double startingBalance = keyboard.nextDouble();
double finalBalance=0;
int years = 0;
int months = 0;
int days = 0;
System.out.println("Please enter the ann1ual interest rate in decimal form: ");
double interestRateYearly = keyboard.nextDouble();
double interstRateMonthly = interestRateYearly;
double interstRateDayliy = interestRateYearly;
while (years<10) {
double interest = startingBalance * interestRateYearly ;
finalBalance = startingBalance + interest;
years++;
}
System.out.println("Balance after 10 years with annual interest is " + finalBalance);
while (months<120) {
double interest = startingBalance * interstRateMonthly /12;
finalBalance = startingBalance + interest;
months++;
}
System.out.println("Balance after 10 years with monthly interest rate is " + finalBalance);
}
}

return issue for method

I am having an issue with a method returning to the main method. It is saying that amount in "return amount" cannot be resolved to a variable. Where am I off on this??
This is the message I get:
Multiple markers at this line
- Void methods cannot return a
value
- amount cannot be resolved to a
variable
Here is the code:
import java.util.Scanner;
public class Investment {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount invested: ");
double amount = input.nextDouble();
System.out.print("Enter the annual interest rate: ");
double interest = input.nextDouble();
int years = 30;
System.out.print(futureInvestmentValue(amount, interest, years)); //Enter output for table
}
public static double futureInvestmentValue(double amount, double interest, int years) {
double monthlyInterest = interest/1200;
double temp;
double count = 1;
while (count < years)
temp = amount * (Math.pow(1 + monthlyInterest,years *12));
amount = temp;
System.out.print((count + 1) + " " + temp);
}
{
return amount;
}
}
You curly braces are not correct. The compiler - and me - was confused about that.
This should work (at least syntactically):
import java.util.Scanner;
public class Investment {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount invested: ");
double amount = input.nextDouble();
System.out.print("Enter the annual interest rate: ");
double interest = input.nextDouble();
int years = 30;
System.out.print(futureInvestmentValue(amount, interest, years));
}
public static double futureInvestmentValue(
double amount, double interest, int years) {
double monthlyInterest = interest / 1200;
double temp = 0;
double count = 1;
while (count < years)
temp = amount * (Math.pow(1 + monthlyInterest, years * 12));
amount = temp;
System.out.print((count + 1) + " " + temp);
return amount;
}
}
Remove amount from its own scope As a start. Also from the method futureInvestmentValue, you take in amount as an argument but the value is never modified so you're returning the same value being passed which is most likely not the desired outcome.
remove return amount from its own scope
the method futureInvestmentValue... You can't modify any of the parameters inside the method so you have to declare another variable besides amount inside the method (maybe it's the temp variable you keep using) and return that instead
when you return something, the return statement is always inside the method. Never outside it while inside its own braces (never seen this before...)
import java.util.Scanner;
public class Investment {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount invested: ");
double amount = input.nextDouble();
System.out.print("Enter the annual interest rate: ");
double interest = input.nextDouble();
int years = 30;
System.out.print(futureInvestmentValue(amount, interest, years)); //Enter output for table
}
public static double futureInvestmentValue(double amount, double interest, int years) {
double monthlyInterest = interest/1200;
double temp;
double count = 1;
while (count < years) {
temp = amount * (Math.pow(1 + monthlyInterest,years *12));
System.out.print((count + 1) + " " + temp);
}
return amount;
}
}

Categories

Resources