How do I display how many months it took? - java

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

Related

How to fix program and NOT receive "Command Execution Failed" error message in Java?

This is my first class and first time using Java. I also need to display 'Employee Name, Rate of Pay, Hours Worked, Overtime Worked, Gross Pay, Total amount of deductions, & Net Pay in the program as well.
package calculatepayprogram;
import java.util.Scanner;
/**
* Calculate Pay Program
* CPT 307: Data Structures & Algorithms
* 7/5/2022
*/
public class CalculatePayProgram{
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
double RateOfPay;
int HoursWorked;
double GrossPay;
double OvertimeHours;
double OvertimePay;
double NetPay;
double TotalDeductions;
String name;
System.out.println("Enter Your Name: ");
name = reader.nextLine();
System.out.print("Enter Your Pay Per Hour: ");
RateOfPay = reader.nextDouble();
System.out.print("Enter Your Hours Worked: ");
HoursWorked = reader.nextInt();
System.out.print("Enter Your Overtime Hours Worked: ");
OvertimeHours = reader.nextDouble();
GrossPay = RateOfPay * HoursWorked;
OvertimePay = OvertimeHours * 1.5 * RateOfPay;
double Pay = OvertimePay + GrossPay;
System.out.println("Your Gross Pay For This Week Will Be $" + Pay);
double FederalTax = .15 * Pay;
double StateTax = .0307 * Pay;
double Medicare = .0145 * Pay;
double SocialSecurity = .062 * Pay;
double Unemployment = .0007 * Pay;
double TotalDeduct = FederalTax + StateTax + Medicare + SocialSecurity + Unemployment;
System.out.println("Your Total Deductions For This Week Will Be $" + TotalDeduct);
NetPay = Pay - TotalDeduct;
System.out.println("Your Net Pay For This Week Will Be $" + NetPay);
}
}

java loop to repeat program

I am extremely new to java I am in my second week in classes or so--
I need my program to keep going or exit according to the user. It is a payroll calculation and I want the end to say "Do you want to continue (y/n)" I want Y to repeat my entire program of questions and no to end program. I am using Jgrasp and I am very very new. I am assuming it needs a loop and I am not totally sure, I just got this to run and compile correctly-- it runs correctly for me so it is a good start and I am hoping to get help on how to do this as I am seeing a ton of different ways and different programs for it. thanks.
import java.util.Scanner;
public class calculations {
public static void main(String [] args) {
Scanner reader = new Scanner(System.in);
Scanner in = new Scanner(System.in);
double Regpay;
double Payperhour;
int HoursAweek;
double Pay;
double OvertimeHours;
double OvertimePay;
double Dependants;
double SocSecTax;
double FederalTax;
double StateTax;
int UnionDues;
double AllTaxes;
double FinalPay;
String playAgain;
System.out.print("Enter your pay per hour:");
Payperhour = reader.nextDouble ();
System.out.print("Enter your regular Hours a week:");
HoursAweek = reader.nextInt();
System.out.print("Enter your overtime hours:");
OvertimeHours = reader.nextDouble();
Regpay = Payperhour * HoursAweek;
OvertimePay = OvertimeHours * 1.5 * Payperhour;
Pay = OvertimePay + Regpay;
SocSecTax = Pay * .06;
FederalTax = Pay * .14;
StateTax = Pay * .05;
UnionDues = 10;
AllTaxes = SocSecTax + FederalTax + StateTax + UnionDues;
FinalPay = Pay -= AllTaxes;
System.out.println("Your pay this week will be " +FinalPay);
{
System.out.println("How many Dependants:");
Dependants = reader.nextInt();
if (Dependants >= 3) {
Dependants = Pay + 35;
System.out.println("Your Pay is:" +Dependants);
} else if(Dependants < 3) {
System.out.println("Your Pay is:" +Pay);
}
}
}
}
Here is the basic idea with your code:
import java.util.Scanner;
public class calculations{
public static void main(String [] args) {
Scanner reader = new Scanner(System.in);
Scanner in = new Scanner(System.in);
double Regpay;
double Payperhour;
int HoursAweek;
double Pay;
double OvertimeHours;
double OvertimePay;
double Dependants;
double SocSecTax;
double FederalTax;
double StateTax;
int UnionDues;
double AllTaxes;
double FinalPay;
String playAgain;
int runAgain = 1;
while (runAgain == 1) {
System.out.print("Enter your pay per hour:");
Payperhour = reader.nextDouble();
System.out.print("Enter your regular Hours a week:");
HoursAweek = reader.nextInt();
System.out.print("Enter your overtime hours:");
OvertimeHours = reader.nextDouble();
Regpay = Payperhour * HoursAweek;
OvertimePay = OvertimeHours * 1.5 * Payperhour;
Pay = OvertimePay + Regpay;
SocSecTax = Pay * .06;
FederalTax = Pay * .14;
StateTax = Pay * .05;
UnionDues = 10;
AllTaxes = SocSecTax + FederalTax + StateTax + UnionDues;
FinalPay = Pay -= AllTaxes;
System.out.println("Your pay this week will be " + FinalPay);
{
System.out.println("How many Dependants:");
Dependants = reader.nextInt();
if (Dependants >= 3) {
Dependants = Pay + 35;
System.out.println("Your Pay is:" + Dependants);
} else if (Dependants < 3) {
System.out.println("Your Pay is:" + Pay);
}
}
System.out.println("Again??? Press 1 to run again and 0 to exit");
runAgain = reader.nextInt();
}
}
}
Here's a guide for you..
You can create a method for the transaction.
//Place this on your main method
do{
//call the method
transaction();
//ask if the user wants to repeat the program
System.out.print("Do you want to continue (y/n)");
input = reader.nextLine();
}while(input.equalsIgnoreCase("Y"))
public void transaction(){
//your transaction code here..
}
Here is a brief idea of how to do this:
String choice = "y";
while(true) {
//Take input
System.out.print("Do you want to continue (y/n)?");
choice = reader.nextLine();
if(choice.equalsIgnoreCase("n")) break;
//else do your work.
}
You can also sue do-while to get what you want. You may need to make some changes but then that is the entire idea. It is just a hint.

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)

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

Categories

Resources