Reading The Calculation Wrong with math pow - java

am only getting the interest amount an not the amount i suppose to pay a month can you please tell me where am going wrong thanks.
import java.util.Scanner;
/**
*
* #author
*/
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 payment type:");
String period = input.next();
System.out.print("Enter Loan Length :");
int length = input.nextInt();
//proces
rate = interest / 100;
if (period.equals("monthly")) {
double n = length * 12;
payment = principal * (rate * Math.pow((1 + rate), n) / Math.pow((1 + rate), n));
System.out.printf("Your Monthly Sum is %.2f",payment);
}
}

Your error is here:
principal * rate * Math.pow((1 + rate), n) / Math.pow((1 + rate), n)
This is the same as having only principal * rate. You are saying x = b * a / a.
Replace to:
payment = principal * Math.pow((1 + rate), n);
n is the number of years, you can not do n = length / 12 to get Monthly. You should do instead:
payment = (principal * Math.pow((1 + rate), n)) / 12;

It should be
payment = principal * Math.pow((1 + rate), n);
As
A=P((1+rate/100)^n)

Related

I'm making a payroll using Java. Why am I getting the wrong net pay if my mathematical formulas seem correct?

I'm making a payroll calculator. The first person worked 38.00 hours with a pay rate of $8.75. The second person worked 46.50 hours with a pay rate of $17.00. It's obvious the second person worked overtime. I'm experiencing issues when calculating the net pay as well as the gross pay. The second person's net pay should be $718.89. I keep getting $140.89. The issues only happen if the person works overtime (>40). Is there a problem with my if statement? I'd like some advice. I've been learning Java for 2 weeks now, excuse the mistakes.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
final byte PERCENT = 15;
// Tax is 15%
final float taxRate = PERCENT / (float) 100;
Scanner scanner = new Scanner(System.in);
System.out.print("First Name: ");
String firstName = scanner.next().trim();
System.out.print("Last Name: ");
String lastName = scanner.next().trim();
System.out.println(lastName + ", " + firstName);
System.out.print("Pay Rate: ");
float payRate = scanner.nextFloat();
System.out.print("Hours Worked: ");
float totalHours = scanner.nextFloat();
// regular hours = total hours if less than 40
// overtime = total hours - 40
float regularPay = 0;
if (totalHours <= 40) {
regularPay = totalHours * payRate;
}
float overTimePay = 0;
if (totalHours > 40) {
overTimePay = (float) ((totalHours - 40) * 1.5 * payRate);
}
final double grossPay = (double) regularPay + (double) overTimePay;
System.out.println("Gross Pay: " + (Math.round(grossPay * 100.0) / 100.0));
final double taxAmount = grossPay * taxRate;
System.out.println("Tax Amount: " + (Math.round(taxAmount * 100.0) / 100.0));
final double netPay = grossPay - taxAmount;
System.out.println("Net Pay: " + (Math.round(netPay * 100.0) / 100.0));
}
}
if totalHours > 40, regularPay will be 0 in your code.
you should change the condition to something like this.
if totalHours > 40, first calculate regularPay for 40 hours
overtimepay should be remaining hours (totalhours -40)
your regularPay variable is only being recorded if hours<=40. You need to put something in your second if statement to set your regularPay variable. You probably want something like:
regularPay = 40*payRate;
Include this in your second if statement

Change Calculator Subtracting One

My calculator in Java will not output the correct amount of change. It subtracts one penny and I am not sure why.
I initially declared the change as separate variables but I then just multiplied the users input by 100, but I still have the same problem.
//this is where the variables are declared
double penny = 0.01;
double nickel = 0.05;
double dime = 0.10;
double quarter = 0.25;
double half_dollar = 0.50;
double dollar_coin = 1.00;
double user_input = 0;
int total_penny, total_nickel, total_dime, total_quarter,
total_half_dollar, total_dollar_coin;
Scanner in = new Scanner (System.in);
//this is where the user can input data
System.out.println("What amount would you like change for: ");
user_input = in.nextDouble();
//this is where the users data will be processed
total_dollar_coin = (int) (user_input / 1.0);
user_input = user_input % 1.00;
total_half_dollar = (int) (user_input / 0.50);
user_input = user_input % 0.50;
total_quarter = (int) (user_input / 0.25);
user_input = user_input % 0.25;
total_dime = (int) (user_input / 0.10);
user_input = user_input % 0.10;
total_nickel = (int) (user_input / 0.05);
user_input = user_input % 0.01;
total_penny = (int) (user_input / 0.01);
//this is where the information will be outputted to the user
System.out.println("Your change will be: " + total_dollar_coin + " dollar
coin(s) ");
System.out.println(total_half_dollar + " half dollar coin(s) " +
total_quarter
+ " quarter(s) ");
System.out.print(total_dime + " dime(s) " + total_nickel + " nickel(s) " +
total_penny + " penny (or pennies) ");
}
}
If you debug this, you will see that for e.g. 51.43 your last line:
total_penny = (int) (user_input / 0.01);
results in something like:
Since you are casting to int, this will result in "unexpected output", in this case zero (0) - see link provided above in the second comment regarding accuracy.
Nonetheless, a possible solution to the problem (as an educational exercise) is to do the following:
BigDecimal total_penny;
int total_nickel, total_dime, total_quarter, total_half_dollar, total_dollar_coin;
And then in your total_penny line:
user_input = user_input % 0.05; --> you have 0.01 typo here
total_penny = BigDecimal.valueOf(user_input / 0.01);
Format the total_penny output and output that:
String penny = NumberFormat.getInstance().format(total_penny);
System.out.println("..." + penny + " penny (or pennies) ");
This will give you the amount you expect:

Java Loan Calculator nested for loop based on user input

The task is to create a loan calculator based on the user input of min and max years of loan payments, loan amount, and min and max % rate with incremented value given by user as well for rate and number of years.
Desired output should look like this:
Principle: $275000.0
Years to repay: 10
Interest Monthly
Rate Payment
6.25 3087.7
6.75 3157.66
7.25 3228.53
Principle: $275000.0
Years to repay: 15
Interest Monthly
Rate Payment
6.25 2357.91
6.75 2433.5
7.25 2510.37
Principle: $275000.0
Years to repay: 20
Interest Monthly
Rate Payment
6.25 2010.05
6.75 2091.0
7.25 2173.53
Please help me fix errors. Thanks!
public static void main(String[] args){
Scanner console = new Scanner (System.in);
System.out.println("This program computes monthly " + "mortgage payments.");
System.out.print("Enter the loan amount: ");
double loan = console.nextDouble();
System.out.print("Enter the starting number of years to repay the loan: ");
int startingYears = console.nextInt();
System.out.print("Enter the ending number of years to repay the loan: ");
int endingYears = console.nextInt();
System.out.print("Enter the years increment between tables: ");
int incrementYears = console.nextInt();
System.out.print("Enter the starting loan yearly interest rate, %: ");
double startingRate = console.nextDouble();
System.out.print("Enter the ending loan yearly interest rate, %: ");
double endingRate = console.nextDouble();
System.out.print("Enter the increment interest rate, %: ");
double incrementRate = console.nextDouble();
System.out.println();
System.out.println("Principle: $" + (double) loan);
System.out.printf("Years to repay: %d\n", startingYears);
System.out.println("-------- -------");
double payment;
System.out.println("Rate\tPayment");
for (int j = startingYears; j <= endingYears; incrementYears++) {
for (double i = startingRate; i <= endingRate; incrementRate++){
int n = 12 * startingYears;
double c = startingRate / 12.0 / 100.0;
payment = loan * c * Math.pow(1 + c, n) / (Math.pow(1 +c, n) - 1);
System.out.println(i + " " + payment);
// System.out.println(round2(startingRate) + "\t" + round2(payment));
startingYears += incrementYears;
}
}
}
}
for (int j = startingYears; j <= endingYears; incrementYears++) {
for (double i = startingRate; i <= endingRate; incrementRate++) {
You are never incrementing the values of your counters i.e. i and j and hence the values of i and j will always be equal to the initialized values and these loops will run for infinite times.
Increment both the counters to be able to reach the termination condition i.e. j <= endingYears and i <= endingRate respectively.
Here is the code snippet:
System.out.println("Principle: $" + (double) loan);
for (int j = startingYears; j <= endingYears; j+=incrementYears) {
System.out.printf("Years to repay: %d\n", j);
System.out.println("-------- -------");
System.out.println("Rate\tPayment");
for (double i = startingRate; i <= endingRate; i+=incrementRate){
int n = 12 * j;
double c = i / 12.0 / 100.0;
double payment = loan * c * Math.pow(1 + c, n) / (Math.pow(1 + c, n) - 1);
System.out.println(i + "\t" + payment);
}
System.out.println();
}

Math.pow difficulty

When I enter 1000 for investment amount 4.25 for monthly interest rate and 1 for years, why do I get the result 4.384414858452464E11 instead of the expected 1043.34?
import java.util.Scanner;
public class FinancialApplicationFutureInvestment_13 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter investment amount: ");
int investmentAmount = input.nextInt();
System.out.println("Enter monthly interest rate: ");
double monthlyInterestRate = input.nextDouble();
System.out.println("Enter number of years");
int numOfYears = input.nextInt();
double futureInvestmentValue = investmentAmount *
(Math.pow(1 + monthlyInterestRate, numOfYears * 12));
System.out.println("Accumulated value is: " + futureInvestmentValue);
double test = Math.pow(1 + monthlyInterestRate, numOfYears * 12);
System.out.println(test);
}
}
Monthly interest rate will probably need to be entered as 0.0425
1 + monthlyInterestRate
Is monthlyInterestRate a raw factor, or is it expressed in percentage points?
Try dividing by one hundred.
the formula is
A = P(1+r/100)^n
so it should be
investmentAmount * (Math.pow(1 + (monthlyInterestRate/100), numOfYears * 12));
well, you compute 1+4.25 (5.25) as monthly interest rate, instead of 1+(4.25/100) .
you should use casting in System.out.println (double to int) --
(int)(futureInvestmentValue * 100) / 100.0

Problem Printing From My Method

Merged with Java JOptionPane Output.
I am new to Java and I have been going crazy trying to get this to work.
I have been trying to get this Print Method to work for the last couple of hour but I just can't figure out what is wrong with it. I don't get any errors when I run it. I only want one output box to display after all of the calculations have been made.
I need to ask the user the following information and display the output for the following:
Number of loans to compare
House Price
Down Payment
My Problem: Something is a matter with my math and the output box is displaying more than once.
I greatly appreciate any help I can get with this. Thanks In Advance!
package javamortgagecalculator;
import javax.swing.JOptionPane;
public class JavaMortgageCalculator {
public static void main(String[] args) {
int numberOfLoans;
double sellingPrice;
double downPayment;
double loanAmount;
double annualInterestRate = 0.0;
int numberOfYears = 0;
double[] interestRatesArr;
int[] numberOfYearsArr;
double[] monthlyPayment;
//A. Enter the Number Of Loans to compare and Convert numberOfLoansString to int
String numberOfLoansString = JOptionPane.showInputDialog("Enter the Number Of Loans to Compare");
numberOfLoans = Integer.parseInt(numberOfLoansString);
//B. Enter the Selling Price of Home Convert homeCostString to double
String sellingPriceString = JOptionPane.showInputDialog("Enter the Loan Amount");
sellingPrice = Double.parseDouble(sellingPriceString);
//C. Enter the Down Payment on the Home
String downPaymentString = JOptionPane.showInputDialog("Enter the down payment on the Home");
downPayment = Double.parseDouble(downPaymentString);
//Get the loanAmount by Subtracting the Down Payment from homeCost
loanAmount = sellingPrice - downPayment;
interestRatesArr = new double[numberOfLoans];
numberOfYearsArr = new int[numberOfLoans];
monthlyPayment = new double[numberOfLoans];
int counter = 1;
for (int i = 0; i < numberOfLoans; i++) {
//Enter the Interest Rate
String annualInterestRateString = JOptionPane.showInputDialog("Enter the interest rate for Scenario " + counter);
annualInterestRate = Double.parseDouble(annualInterestRateString);
interestRatesArr[i] = (annualInterestRate);
//D2 Get the number of years
String numberOfYearsString = JOptionPane.showInputDialog("Enter the number of years for Scenario " + counter);
numberOfYears = Integer.parseInt(numberOfYearsString);
numberOfYearsArr[i] = (numberOfYears);
counter++;
}
printArray(numberOfLoans,
sellingPrice,
downPayment,
loanAmount,
annualInterestRate,
numberOfYears,
interestRatesArr,
numberOfYearsArr,
monthlyPayment);
}
//public static void printArray(int numOfLoans, double price, double dwnPayment, double loanAmt, double[] printRate, int[] printYears) {
public static void printArray(int numberOfLoans2,
double sellingPrice2,
double downPayment2,
double loanAmount2,
double annualInterestRate2,
int numberOfYears2,
double[] interestRatesArr2,
int[] numberOfYearsArr2,
double[] monthlyPayment2){
for (int i = 0; i < numberOfLoans2; i++) {
//Calculate monthly payment
double monthlyPayment = loanAmount2 * annualInterestRate2 / (1 - 1 / Math.pow(1 + annualInterestRate2, numberOfYears2 * 12));
//Format to keep monthlyPayment two digits after the decimal point
monthlyPayment = (int) (monthlyPayment * 100) / 100.0;
//Store monthlyPayment values in an array
monthlyPayment2[i] = (monthlyPayment);
//Calculate total Payment
double totalPayment = monthlyPayment2[i] * numberOfYears2 * 12;
//Format to keep totalPayment two digits after the decimal point
//totalPayment = (int) (totalPayment * 100) / 100.0;
//totalPaymentArray[i] = (totalPayment);
StringBuilder sb = new StringBuilder();
int n = 0;
for (int x = 0; x < numberOfLoans2; x++) {
if (n == 0) {
sb.append(String.format("%s\t\t %s\t\t %s\t\t %s\t\t %s\t\t %s\t\t %n", "Selling Price", "Down Payment", "Loan Amount", "Rate", "Years", "Payment"));
}
sb.append(String.format("%s\t\t\t\t %s\t\t\t\t\t\t %s\t\t\t\t\t\t\t\t %s\t\t\t\t\t\t\t\t %s\t\t\t\t\t\t %s\t\t\t\t %n", "$" + sellingPrice2, "$" + downPayment2, "$" + loanAmount2, interestRatesArr2[i] + "%", numberOfYearsArr2[i], "$" + monthlyPayment2[i]));
n++;
}
String toDisplay = sb.toString();
JOptionPane.showMessageDialog(null, sb.toString(), toDisplay, JOptionPane.INFORMATION_MESSAGE);
}
}
}

Categories