Having trouble with the math for a loan calculator program - java

This is a loan calculator program. I'm having trouble with the math. Everything else seems to be correct except for the value of the beginning balance after 2 months. Notice that the beginning balance of the 3rd month is different from the ending balance of the 2nd month. Same thing for the succeeding months. I've been trying to fix it but everything didn't work out. I need them to be the same so the ending balance of the last month will be 0.
This is a sample output of the program:
Personal Loan Payment Calculator
Enter a loan amount: 1000
Enter the loan term (months): 6
Enter the interest rate (% per year): 9
Loan Payment and Amortization Table
Months Beginning Monthly Principal Interest Ending
Balance Payment Paid Paid Balance
1 1000.00 171.07 163.57 7.50 836.43
2 836.43 171.07 164.80 6.27 671.64
3 670.41 171.07 166.04 5.03 504.37
4 501.88 171.07 167.30 3.76 334.57
5 330.78 171.07 168.59 2.48 162.19
6 157.06 171.07 169.89 1.18 -12.83
Summary:
========
Loan Amount: $1,000.00
Monthly Payment: $171.07
Number of Payments: 6
Total Interest Paid: $24.00
Annual Interest Rate: 9.00%
This is the program:
public class LoanCalculator {
public static void main(String[] args) {
System.out.println("Personal Loan Payment Calculator"); // print the name of the program
System.out.println("================================");
Scanner keyboard = new Scanner (System.in); // define a Scanner object attached to a keyboard
String badInput; // assign non-integer or non-double inputs to badInput
System.out.print("Enter a loan amount: "); // prompt the user to enter loan amount
while ( ! keyboard.hasNextDouble()) // is the first input value a double?
{
badInput = keyboard.next();
System.out.println("Error: expected a Double, encountered: " + badInput);
System.out.println("Please enter a loan amount in Double: ");
}
double loanAmount = keyboard.nextDouble(); // assign the first input to loanAmount
System.out.print("Enter the loan term (months): "); // prompt the user to enter number of months
while ( ! keyboard.hasNextInt()) // is the second input value an int?
{
badInput = keyboard.next();
System.out.println("Error: expected an Integer, encountered: " + badInput);
System.out.println("Please enter a loan term in Integer: ");
}
int loanTerm = keyboard.nextInt(); // assign the second input to loanTerm
System.out.print("Enter the interest rate (% per year): "); // prompt the user to enter the interest rate
while ( ! keyboard.hasNextDouble()) // is the first input value a double?
{
badInput = keyboard.next();
System.out.println("Error: expected an integer, encountered: " + badInput);
System.out.println("Please enter a loan amount in Double: ");
}
double interestRate = keyboard.nextDouble(); // assign the third input to interestRate
System.out.println(); // skip a line
System.out.println(" Loan Payment and Amortization Table");
System.out.printf("%s", "=============================================================");
System.out.println();
System.out.printf("%5s %10s %10s %10s %10s %10s", "Months" ,"Beginning", "Monhtly", "Principal", "Interest", "Ending");
System.out.println();
System.out.printf(" %5s %10s %10s %10s %10s %10s", "#","Balance", "Payment", "Paid", "Paid", "Balance");
System.out.println();
System.out.printf("%s ", "=============================================================");
System.out.println();
double monthlyRate = (interestRate / 100.0) / 12.0;
double monthlyPayment = (monthlyRate * loanAmount) / ( 1 - (Math.pow( 1 + monthlyRate, - loanTerm)));
double beginningBalance = loanAmount;
double interestPaid = beginningBalance * monthlyRate;
double principalPaid = monthlyPayment - interestPaid;
int total_interest_paid = 0;
for (int monthCount = 0 ; monthCount < loanTerm ; ++monthCount)
{
int months = 1 + monthCount;
beginningBalance = loanAmount - principalPaid * monthCount;
interestPaid = beginningBalance * monthlyRate;
principalPaid = monthlyPayment - interestPaid;
double endingBalance = beginningBalance - principalPaid;
System.out.printf(" %5d %10.2f %10.2f %10.2f %10.2f %10.2f\n", months, beginningBalance, monthlyPayment, principalPaid, interestPaid, endingBalance);
total_interest_paid += interestPaid;
}
System.out.printf("%s ", "=============================================================");
System.out.println();
NumberFormat currency = NumberFormat.getCurrencyInstance();
DecimalFormat percentFormat = new DecimalFormat ("0.00");
System.out.println("\nSummary:");
System.out.println("========");
System.out.println("Loan Amount: " + currency.format(loanAmount));
System.out.println("Monthly Payment: " + currency.format(monthlyPayment));
System.out.println("Number of Payments: " + loanTerm);
System.out.println("Total Interest Paid: " + currency.format(total_interest_paid));
System.out.println("Annual Interest Rate: " + percentFormat.format(interestRate) + "%");
}
}

The error is very simple:
beginningBalance = loanAmount - principalPaid * monthCount;
Remember that "principalPaid" increases every month. The total principal paid is not the last principalPaid * mouthCount but the sum of the principal paid in all months.
You could create a running total for principalPaid like you did for interest paid.
But it would be much easier to do beginningBalance = previous month endingBalance.

Related

java string.format doubles issue

just need help with formatting a string to look like this:
Here is your tax breakdown:
Income $25,000.00
Dependants 1
----------------------------
Federal Tax $4,250.00
Provincial Tax $1,317.75
============================
Total Tax $5,567.75"
heres my code, please help me format as above with spaces and decimals
import java.util.Scanner;
public class HelloWorld {
public static void main(String args[]) {
double income, fedTax, provTax;
int dependents;
Scanner input = new Scanner(System.in);
System.out.print("Please enter your taxable income: ");
income = input.nextInt();
System.out.println();
System.out.print("Please enter your number of dependents: ");
dependents = input.nextInt();
System.out.println();
if (income <= 29590) {
fedTax = 0.17 * income;
}
else if (income <= 59179.99) {
fedTax = 0.17 * 29590 + 0.26 * (income - 29590);
}
else {
fedTax = 0.17 * 29590 + 0.26 * 29590 + (0.29 * (income - 59180));
}
double base = 42.5 * fedTax;
double deductions = 160.50 + 328 * dependents;
provTax = base - deductions;
if (base < deductions) {
provTax = 0;
}
else {
provTax = base - deductions;
}
double totalTax = fedTax + provTax;
System.out.println("Here is your tax breakdown: ");
System.out.println(String.format(" Income%,10.d", income));
System.out.println(String.format(" Dependants%10.d", dependents));
System.out.println("-------------------------");
System.out.println(String.format(" Federal Tax%,10.2f", fedTax));
System.out.println(String.format("Provincial tax%,10.2f", provTax));
System.out.println("=========================");
System.out.println(String.format(" Total Tax%,10.2f", totalTax));
}
}
please ignore down here this is just to let me post because there isnt enough words, even though my question does not to be detailed :(
If the income variable is declared a double data type then you can't expect to fill that variable using the Scanner#nextInt() method which is expecting the User to enter an Integer value whereas you want to enter a double (floating point) value. At the very least you want to use the Scanner#nextDouble() method.
I don't think your calculations for Provincial Tax is correct. If it is then I sure wouldn't want to deal with that bill. I'm not going to try and figure that one out but this is rather suspect to start with:
double base = 42.5 * fedTax;
double deductions = 160.50 + 328 * dependents;
provTax = base - deductions; // deductions removed from base here...
if (base < deductions) {
provTax = 0;
}
else {
provTax = base - deductions; // and yet again here....hmmmm
}
To get the formatting you want you would want to possibly utilize both the String#format() method along with the DecimalFormat#format() method and possibly a couple of its' other methods (read end note), for example:
// Set the numerical format you want.
java.text.DecimalFormat decimalFormat = new java.text.DecimalFormat("0.00");
decimalFormat.setGroupingUsed(true); // You want comma grouping
decimalFormat.setGroupingSize(3); // Comma every 3 digits
System.out.println("Here is your tax breakdown: ");
System.out.println(String.format("Income %20s", "$" + decimalFormat.format(income)));
System.out.println(String.format("Dependants %16d", dependents));
System.out.println("---------------------------");
System.out.println(String.format("Federal Tax %15s", "$" + decimalFormat.format(fedTax)));
System.out.println(String.format("Provincial Tax %12s", "$" + decimalFormat.format(provTax)));
System.out.println("===========================");
System.out.println(String.format("Total Tax %17s", "$" + decimalFormat.format(totalTax)));
Your entire code with the above modification and the fix for the income prompt (using the Scanner#nextDouble() method) would look something like this:
double income, fedTax, provTax;
int dependents;
Scanner input = new Scanner(System.in);
System.out.print("Please enter your taxable income: ");
income = input.nextDouble();
System.out.println();
System.out.print("Please enter your number of dependents: ");
dependents = input.nextInt();
System.out.println();
if (income <= 29590) {
fedTax = 0.17 * income;
}
else if (income <= 59179.99) {
fedTax = 0.17 * 29590 + 0.26 * (income - 29590);
}
else {
fedTax = 0.17 * 29590 + 0.26 * 29590 + (0.29 * (income - 59180));
}
double base = 42.5 * fedTax;
double deductions = 160.50 + 328 * dependents;
provTax = base - deductions;
if (base < deductions) {
provTax = 0;
}
else {
provTax = base - deductions;
}
double totalTax = fedTax + provTax;
// Set the numerical format you want.
java.text.DecimalFormat decimalFormat = new java.text.DecimalFormat("0.00");
decimalFormat.setGroupingUsed(true); // You want comma grouping
decimalFormat.setGroupingSize(3); // Comma every 3 digits
System.out.println("Here is your tax breakdown: ");
System.out.println(String.format("Income %20s", "$" + decimalFormat.format(income)));
System.out.println(String.format("Dependents %16d", dependents));
System.out.println("---------------------------");
System.out.println(String.format("Federal Tax %15s", "$" + decimalFormat.format(fedTax)));
System.out.println(String.format("Provincial Tax %12s", "$" + decimalFormat.format(provTax)));
System.out.println("===========================");
System.out.println(String.format("Total Tax %17s", "$" + decimalFormat.format(totalTax)));
If you were to run this code now, you should see in the Console Window the following (if you supply the same values):
Please enter your taxable income: 25500.54
Please enter your number of dependents: 1
Here is your tax breakdown:
Income $25,500.54
Dependents 1
---------------------------
Federal Tax $4,335.09
Provincial Tax $183,752.90
===========================
Total Tax $188,087.99
What a tax bill for 25.5 grand. :/
Note: You can eliminate the use of the DecimalFormat#setGroupingUsed() and the DecimalFormat#setGroupingSize() methods if you initialize your decimalformat variable with:
DecimalFormat decimalFormat = new DecimalFormat("#,###,##0.00");

Calculating double diminishing depreciation using loops

So I have to come up with a code that calculates depreciation using double diminishing method.
So far I got this code:
Scanner kbd = new Scanner (System.in);
System.out.println("Please enter asset number: ");
assetNum = kbd.nextInt();
System.out.println("Please enter initial purchase price: ");
purchPrice = kbd.nextDouble();
System.out.println("Please enter useful life of the asset (in years): ");
usefulLife = kbd.nextDouble();
System.out.println("Please enter the salvage value: ");
salvageVal = kbd.nextDouble();
System.out.println("Please enter the number of years of depreciation: ");
numYears = kbd.nextDouble();
ddRate = ((1.0 / usefulLife) * 2) * 100;
System.out.println("Asset No: " + assetNum);
System.out.printf("Initial Purchase Price: $%,.0f%n" , purchPrice);
System.out.printf("Useful Life: %.0f years%n" , usefulLife);
System.out.printf("Salvage Value: $%,.0f%n" , salvageVal);
System.out.printf("Double Declining Rate: %.0f%%%n" , ddRate);
System.out.printf("Number of Years: %.0f years%n" , numYears);
System.out.println();
System.out.println("Year Yearly Accumulated Book");
System.out.println(" Depreciation Depreciation Value");
System.out.println();
int year;
double yearlyDepr;
double accDepr;
double bookVal;
bookVal = purchPrice;
accDepr = 0;
year = 0;
while (bookVal >= salvageVal){
yearlyDepr = bookVal * (ddRate / 100);
accDepr = accDepr + yearlyDepr;
bookVal = bookVal - yearlyDepr;
year++;
System.out.printf("%d %,18.0f %,18.0f %,18.0f%n" , year, yearlyDepr, accDepr, bookVal);
}
}
}
The output looks good until the last row with a book value of 7,776 instead of the salvage value of 10,000.
Mines like this:
http://puu.sh/zyGzg/e35ccf0722.png
Should be like this:
http://puu.sh/zyGBM/4b6b8fa14c.png
Please help, I'm really stuck.
In your while loop you need to test if the new bookVal will be less than salvageVal and if so use the salvageVal
while (bookVal > salvageVal){ // also change
yearlyDepr = bookVal * (ddRate / 100);
accDepr = accDepr + yearlyDepr;
bookVal = bookVal - yearlyDepr;
year++;
if (bookVal < salvageVal) {
bookVal = salvageVal;
yearlyDepr = purchPrice - salvageVal;
}
System.out.printf("%d %,18.0f %,18.0f %,18.0f%n" , year, yearlyDepr, accDepr, bookVal);
}

Finding out how much of a total amount each variable represents? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am trying to find out how much of the total amount variable 1 is responsible for and how much of the total cost variable 2 is responsible for. I have attached an image of my source code so far
the assignment instructions are: The program will then calculate the total of all the expenses, what each person should pay if the costs were divided equally, and how much each friend actually paid. If one person paid less than the other, then they will owe their friend some money.
import java.util.Scanner;
public class Trip {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double flight, hotel, meals, tour, total, owes;
String name1, name2;
double Lisa, Bart;
double input1, input2, input3, input4;
Lisa = 1;
Bart = 2;
System.out.print("Enter the first name: ");
name1 = keyboard.nextLine();
System.out.print("Enter the second name: ");
name2 = keyboard.nextLine();
System.out.print("Enter cost of flights: ");
flight = keyboard.nextDouble();
System.out.print("Who paid for the flights: Enter 1 for Lisa or 2 for Bart ");
input1 = keyboard.nextInt();
System.out.print("Enter cost of hotel: ");
hotel = keyboard.nextDouble();
System.out.print("Who paid for the hotel: Enter 1 for Lisa or 2 for Bart ");
input2 = keyboard.nextInt();
System.out.print("Enter cost of tour: ");
tour = keyboard.nextDouble();
System.out.print("Who paid for the tour: Enter 1 for Lisa or 2 for Bart ");
input3 = keyboard.nextInt();
System.out.print("Enter cost of meals: ");
meals = keyboard.nextDouble();
System.out.print("Who paid for the meals: Enter 1 for Lisa or 2 for Bart ");
input4 = keyboard.nextInt();
total = flight + hotel + meals + tour;
System.out.printf("Total bill for trip: %.2f \n", total);
owes = total / 2;
System.out.printf("Each person owes: %.2f", owes);
}
}
Say you have two people Max and Simon. You could do something like below where you first find the amount owed by Max using your logic. And then to find the amount owed by Simon you just use totalCost - amountMaxOwes:
import java.util.Scanner;
class Trip {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first name:");
String nameOne = scanner.nextLine();
System.out.print("Enter the second name:");
String nameTwo = scanner.nextLine();
System.out.print("Enter cost of flights:");
double flightsCost = scanner.nextDouble();
System.out.printf("Who paid for the flights? Enter 1 for %s or 2 for %s:", nameOne, nameTwo);
int whoPaidFlights = scanner.nextInt();
System.out.print("Enter cost of hotel:");
double hotelCost = scanner.nextDouble();
System.out.printf("Who paid for the hotel? Enter 1 for %s or 2 for %s:", nameOne, nameTwo);
int whoPaidHotel = scanner.nextInt();
System.out.print("Enter cost of tour:");
double tourCost = scanner.nextDouble();
System.out.printf("Who paid for the tour? Enter 1 for %s or 2 for %s:", nameOne, nameTwo);
int whoPaidTour = scanner.nextInt();
System.out.print("Enter cost of meals:");
double mealsCost = scanner.nextDouble();
System.out.printf("Who paid for the meals? Enter 1 for %s or 2 for %s:", nameOne, nameTwo);
int whoPaidMeals = scanner.nextInt();
double totalCost = flightsCost + hotelCost + tourCost + mealsCost;
System.out.printf("Total bill for trip: %.2f \n", totalCost);
// This stuff can be moved to a more appropriate place if you want to
double personOnePaid = 0;
if(whoPaidFlights == 1) personOnePaid += flightsCost;
if(whoPaidHotel == 1) personOnePaid += hotelCost;
if(whoPaidTour == 1) personOnePaid += tourCost;
if(whoPaidMeals == 1) personOnePaid += mealsCost;
double personTwoPaid = totalCost - personOnePaid;
System.out.printf("%s owes: %.2f \n", nameOne, personOnePaid);
System.out.printf("%s owes: %.2f \n", nameTwo, personTwoPaid);
}
}
Example Usage:
Enter the first name: Max
Enter the second name: Simon
Enter cost of flights: 299.34
Who paid for the flights? Enter 1 for Max or 2 for Simon: 1
Enter cost of hotel: 300.40
Who paid for the hotel? Enter 1 for Max or 2 for Simon: 2
Enter cost of tour: 55.00
Who paid for the tour? Enter 1 for Max or 2 for Simon: 1
Enter cost of meals: 314.15
Who paid for the meals? Enter 1 for Max or 2 for Simon: 1
Total bill for trip: 968.89
Max owes: 668.49
Simon owes: 300.40

Money format - how do I use it?

I'm a junior in high school. Having a tough time figuring out how to use money format. I'm doing an exercise in A Guide to Programming in Java (Second Edition) where I have to prompt the employees for the number of burgers, fries, and sodas.
Fries are $1.09, burgers are $1.69, and sodas are $0.99.
Here is my code:
import java.util.Scanner;
/**
* Order pg. 101
*
* Garret Mantz
* 2/10/2016
*/
public class Order {
public static void main(String[]args) {
final double pburgers=1.69;
final double pfries=1.09;
final double psodas=0.99;
final double ptax=0.065;
double burgers;
double fries;
double sodas;
double totaltax;
double total;
double tax;
double tendered;
double change;
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount of burgers: ");
burgers = input.nextDouble();
System.out.print("Enter the amount of fries: ");
fries = input.nextDouble();
System.out.print("Enter the amount of sodas: ");
sodas = input.nextDouble();
System.out.print("Enter the amount tendered: ");
tendered = input.nextDouble();
totaltax = (burgers*pburgers)+(fries*pfries)+(sodas*psodas);
tax = totaltax*ptax;
total = totaltax + tax;
change = tendered - total;
System.out.println("Your total before tax is: \n" + totaltax);
System.out.println("Tax: \n" + tax);
System.out.println("Your final total is: \n" + total);
System.out.println("Your change is: \n" + change);
}
}
I just want to use the money format, but I'm not sure how. I'm sure it's a dumb question, but thank you for helping out!
Change your println to these, and see if that helps:
System.out.format("Your total before tax is: $%-5.2f\n", totaltax);
System.out.format("Tax: $%-5.2f\n", tax);
System.out.format("Your final total is: $%-5.2f\n", total);
System.out.format("Your change is: $%-5.2f\n", change);
There is also this:
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String totalTaxString = formatter.format(totaltax);
String taxString = formatter.format(tax);
String totalString = formatter.format(total);
String changeString = formatter.format(change);
System.out.format("Your total before tax is: %s\n", totalTaxString);
System.out.format("Tax: %s\n", taxString);
System.out.format("Your final total is: %s\n", totalString);
System.out.format("Your change is: %s\n", changeString);
Output:
Your total before tax is: $8.53
Tax: $0.55
Your final total is: $9.08
Your change is: $10.92

Java Help Interest Rate [duplicate]

This question already has an answer here:
Possible loss of precision
(1 answer)
Closed 9 years ago.
Hey guys i'm coding this program and i have everything working except for the interest rate which brings out this error,
MenuDrivenProgram.java:92: possible loss of precision
found : double
required: int
deposit = balanceCurrent + interest;
^
1 error
Here is my code,
public static void InvestmentReport()
{
System.out.printf("*** Investment Report stub ***\n");
// This is where your Part A solution goes
System.out.printf("*************** InvestmentReport Menu ***************\n\n");
Scanner console=new Scanner(System.in);
int deposit, monthly, interestRate;
double interest, balanceCurrent;
System.out.println ("Enter your initial deposit amount in dollars\n");
deposit = console.nextInt();
System.out.println ("Enter the annual interest rate as a percentage (eg. 6.0)\n");
interest = console.nextDouble();
System.out.println ("Enter your monthly deposit amount in dollars\n");
monthly = console.nextInt();
System.out.println ("Savings growth over the next 6 months:\n");
System.out.println ("Balance after first month: $" + deposit);
deposit = deposit + monthly;
System.out.println ("Interest earned for this month: $" + interest);
interest = balanceCurrent * interestRate / 12 / 100;
deposit = balanceCurrent + interest;
System.out.println ("Balance after second month: $" + deposit);
deposit = deposit + monthly;
System.out.println ("Interest earned for this month:\n");
System.out.println ("Balance after third month: $" + deposit);
deposit = deposit + monthly;
System.out.println ("Interest earned for this month:\n");
System.out.println ("Balance after fourth month: $" + deposit);
deposit = deposit + monthly;
System.out.println ("Interest earned for this month:\n");
System.out.println ("Balance after fifth month: $" + deposit);
deposit = deposit + monthly;
System.out.println ("Interest earned for this month:\n");
System.out.println ("Balance after sixth month: $" + deposit);
deposit = deposit + monthly;
System.out.println ("Interest earned for this month:\n");
}
Anyone able to tell me what i've done wrong and how to fix it? Cheers
Declare deposit as double.
double deposit = 0D;
Or, you can cast the value to int.
deposit = (int) balanceCurrent + interest;
But deposit is an amount and you should not lose the cent value (decimal part) I suppose.

Categories

Resources