Separate two loops in java - 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);
}
}

Related

NetBeans : Trying to create a class file to work with another program

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(){
}

For loop increments array backwards

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.

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);

Proper Formatting

I have the program working I just need help cutting off the extra numbers, Im not very skilled at using the printf statements when printing in Java. When I run it I get output like 1225.043 Here is what I have:
import java.util.Scanner;
public class Comparison {
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
float amount;
double principal = 1000.00;
double rate;
System.out.println("Enter interest rate");
rate = keyboard.nextDouble();
System.out.println("Year" +" "+ "Amount on deposit");
for(int year = 1; year <= 10; ++year)
{
amount = (float) (principal * Math.pow(1.0 + rate, year));
System.out.println(year+ " "+ amount);
System.out.println();
}
}
}
Try
System.out.printf("%2d %.2f%n", year, amount);
Output:
Enter interest rate
0.1
Year Amount on deposit
1 1100.00
2 1210.00
3 1331.00
4 1464.10
5 1610.51
6 1771.56
7 1948.72
8 2143.59
9 2357.95
10 2593.74

Categories

Resources