How to implement a particular maths formula in Java? - java

package methods;
import java.util.Scanner;
/**
*
* #author Billy
*/
public class Methods {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
double Loanamount; // Loan amount from user
double Aintrate; // User's annual interest rate
double months; // Number of months on loan
double monp; // Monthly payment
double Mintrate; // Monthly interest rate
double n; // The number of payments
// declare an instance of Scanner to read the datastream from the keyboard.
Scanner kb = new Scanner(System.in);
// Get user's loan amount
System.out.print("Please enter your total loan amount: ");
Loanamount = kb.nextDouble();
// Get user's interest rate
System.out.print("Please enter your annual interest rate as a decimal: ");
Aintrate = kb.nextDouble();
// Get user's number of months
System.out.print("Please enter the number of months left on your loan: ");
months = kb.nextDouble();
// Calculate montly interest rate
Mintrate = ((Aintrate / 12));
System.out.println("Your monthly interest rate is " + " " + Mintrate);
// Calculate number of payments
n = ((months * 12));
// Calculate monthly payment
My next job is to find out the monthly payment using this formula.
M = P [ i(1 + i)^n ] / [ (1 + i)^n – 1]
Where
M = monthly mortgage payment
P = The amount borrowed (Loanamount)
i = Monthly interest rate (Mintrate)
n = the number of payments
I tried the following but I just cant figure it out
monp = Loanamount [Mintrate(1+ Mintrate)^n] / [(1+ Mintrate)^n-1 ];

You need to use Math.pow effectivley here.
Try using following in your code
monp = Loanamount*(Mintrate*Math.pow((1+ Mintrate),n)) / (Math.pow((1+ Mintrate),n-1 ) ;

Math.pow is what you need instead of ^. Also you can't use [ or ]. You have to use parenthesis ( and ).
More math functions can be found at:
http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html

The method for ^ is called Math.pow(double a, double b); in Java.
Where a is the number to be raised b times.
Your formula would then look like monp = Loanamount Math.pow((Mintrate(1+ Mintrate), n)) / (Math.pow((1+ Mintrate), n-1));
Reference

You need to call Math.pow(double,double)
OR you could import the required class as..
import static java.lang.Math.pow;
and then use pow() function

Related

How to use System.out.printf() to display output of number to only two decimal places?

I am creating my first java program for the class. The purpose of the program is to calculate interest for deposit for year one and year two. My issue comes when the code outputs the final totals. The last two lines are supposed to use System.out.printf(). I keep getting the error Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = 'i'. How do I correct this?
public static void main(String... args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Hello World!");
//declares variables
double interest = 0;
double balance = 0;
double deposit = 0;
double secondYearBalance = 0;
double secondYearInterest = 0;
//displays welcome message
System.out.println("Welcome to George's Interest Calculator");
//prompts user for input
System.out.println("Please enter your initial deposit:");
deposit = keyboard.nextInt();
//Finds outs interest interest earned on deposit
interest = deposit * TAXRATE;
//Finds out the amount of the balance
balance = deposit + interest;
//finds out second year balance
secondYearInterest = balance * TAXRATE;
secondYearBalance = secondYearInterest + balance;
//Outputs totals
System.out.printf("Your balance after one year with a 4.9% interest rate is $%7.2f %n", balance);
System.out.printf("Your balance after two years with a 4.9% interest rate is $%7.2f %n", secondYearBalance);
System.out.println();
}
The % symbol is used in a printf string for 'put a variable here'.
That's problematic when you write 4.9% interest rate because java thinks that % i is you saying: "a variable goes here". The fix is trivial; a double % is how you write a single percent. Thus:
System.out.printf("Your balance after one year with a 4.9%% interest rate is $%7.2f %n", balance);

When I place my doubles on top, the program doesn't run properly

Assignment: Variables
This program prompts the user to enter a temperature between -58°F and
41°F and a wind speed greater than or equal to 2 then displays then
displays the wind-chill temperature.
// Imports util.Scanner
import java.util.Scanner;
public class Windchill {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Tempurature
double temperature = input.nextDouble();
// Windspeed
double speed = input.nextDouble();
// Compute the wind chill tempurature
double windChill = 35.74 + 0.6215 * temperature -
35.75 * Math.pow(speed,
0.16) + 0.4275 * temperature *
Math.pow(speed, 0.16);
// Prompt the user to enter a temperature between -58F and 41F.
System.out.print("Enter the temperature in Fahrenheit " +
"between -58\u00b0F and 41\u00b0F: ");
// Prompt the user to enter the wind speed greter than or equal to 2.
System.out.print("Enter the wind speed (>= 2) in miles per hour: ");
// Display result
System.out.println("The wind chill tempurature is " + windChill);
}
}
This seems to be a school assignment. However, it seems like you have already completed the bulk of the work. Congratulations! Now, I feel like the issue here can be solved by explaining why your program does not work if "the doubles are on top". I hope that my answer can help you better understand the way java interprets your code!
Without further ado, programming languages of all types have variables. Java is no different. For example...
double number = 0.0; // Java variable declaration
number = 0.0 # Python variable declaration
var number = 0.0 // JavaScript variable declaration
Your code is going to be executed from the top down. An illustration of this would look like the following.
int money = 0;
System.out.println(money);
money = 10;
System.out.println(money);
money = 9000;
System.out.println("I have over " + money);
This will output
0
10
I have over 9000
However, if you wrote this code like the following
System.out.println(money);
int money = 0;
You will get an error! This is because the execution has not seen that money is even a thing yet! This would be like brushing your teeth without a tooth brush. You can't because you don't have a brush.
Therefore, the same applies to your program.
public static void main(String[] args) {
double temperature = input.nextDouble();
Scanner input = new Scanner(System.in);
// Prompt the user to enter a temperature between -58F and 41F.
System.out.print("Enter the temperature in Fahrenheit " +
"between -58\u00b0F and 41\u00b0F: ");
// Tempurature
// Prompt the user to enter the wind speed greter than or equal to 2.
System.out.print("Enter the wind speed (>= 2) in miles per hour: ");
// Windspeed
double speed = input.nextDouble();
// Compute the wind chill tempurature
double windChill = 35.74 + 0.6215 * temperature -
35.75 * Math.pow(speed,
0.16) + 0.4275 * temperature *
Math.pow(speed, 0.16);
// Display result
System.out.println("The wind chill tempurature is " + windChill);
}
Notice temperature above the scanner line. Input is a object you create to read in that double. If you try to use this before you create your input object the program has no idea what that input object is!
Just rearrange the code like below
// Imports util.Scanner
import java.util.Scanner;
public class Windchill {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt the user to enter a temperature between -58F and 41F.
System.out.print("Enter the temperature in Fahrenheit " +
"between -58\u00b0F and 41\u00b0F: ");
// Tempurature
double temperature = input.nextDouble();
// Prompt the user to enter the wind speed greter than or equal to 2.
System.out.print("Enter the wind speed (>= 2) in miles per hour: ");
// Windspeed
double speed = input.nextDouble();
// Compute the wind chill tempurature
double windChill = 35.74 + 0.6215 * temperature -
35.75 * Math.pow(speed,
0.16) + 0.4275 * temperature *
Math.pow(speed, 0.16);
// Display result
System.out.println("The wind chill tempurature is " + windChill);
}
}
but there is no problem related to double, :)
Thanks everyone. I got it.
/* Assignment: Variables
This program prompts the user to enter a temperature between -58°F and 41°F
and a wind speed greater than or equal to 2 then displays then displays the
wind-chill tempurature.
*/
// Imports util.Scanner
import java.util.Scanner;
public class Windchill {
public static void main(String[] args) {
// Declare variables
double temperature;
double windspeed;
double wind_chill;
// Create a Scanner object to read input
Scanner input = new Scanner(System.in);
// Prompt the user to enter a temperature between -58F and 41F.
System.out.print("Enter the temperature in Fahrenheit " +
"between -58\u00b0F and 41\u00b0F: ");
temperature = input.nextDouble();
// Prompt the user to enter the wind speed greter than or equal to 2.
System.out.print("Enter the wind speed (>= 2) in miles per hour: ");
windspeed = input.nextDouble();
// Display result
wind_chill = 35.74 + 0.6215 * temperature -
35.75 * Math.pow(windspeed, 0.16) +
0.4275 * temperature * Math.pow(windspeed, 0.16);
System.out.println("The wind chill temprature is " + wind_chill);
}
}

How to raise a double to a power

Cannot figure out how to raise the formula to a power. I have imported the java.lang.Math in java also. I just keep getting the Sytax error on "Math" delete this token and cannot invoke pow(double) on the primitive data type double errors
This is the formula assuming a 30 year loan
Annuity Factor = (0.003125*(1+0.003125)^360)/(((1+0.003125)^360)-1)
the 360 is 30 years time 12 months to get the monthly payment
import java.util.Scanner;
import java.lang.Math;
public class HW3Method {
public static void main(String[] args) {
// main method for user inputs
Scanner info = new Scanner(System.in);
System.out.println("Enter the starting annual rate as a percent (n.nnn)");
double startRate = info.nextDouble();
System.out.println("Enter the ending annual rate as a percent (n.nnn)");
double endRate = info.nextDouble();
System.out.println("Enter the annual intrest rate increments as a percent (n.nnn)");
double rateIncrease = info.nextDouble();
System.out.println("Enter the first term in years for calculating payments");
double firstTerm = info.nextDouble();
System.out.println("Enter the last term in years for calculating payments");
double lastTerm = info.nextDouble();
System.out.println("Enter the term increment in years");
int termIncrement = info.nextInt();
System.out.println("Enter the loan amount");
double loanAmount = info.nextDouble();
double mtp = firstTerm * 12;
}
public double calcAnnuity(double mtp ) {
double annuityFactor = (0.003125*(1+0.003125)Math.pow(mtp));
return annuityFactor;
}
}
Explanation
You are using the method Math.pow wrong. It wants two arguments, the base and the exponent. You wrote:
0.003125 * (1 + 0.003125) Math.pow(mtp)
But you need to write:
0.003125 * Math.pow(1.0 + 0.003125, mtp)
Notes
Note that 1.0 + 0.003125 can be simplified to just 1.003125, so:
0.003125 * Math.pow(1.003125, mtp)
Even better would be to store that magical number somewhere as constant, then you only need to change one variable and not many:
private static final int FACTOR = 0.003125;
And then use that constant:
FACTOR * Math.pow(1.0 + FACTOR, mtp)
Documentation
From the official documentation of Math.pow:
public static double pow​(double a, double b)
Returns the value of the first argument raised to the power of the second argument. Special cases: [...]

Java Computing Monthly Payments Loops

I have a question for yall, I am using loops for the following program and I cant understand how to make it so it displays each payment per month,
You are going to write a program which will display the payment schedule for a loan given an interest rate and the number of payments.
Prompt the user for a loan amount, the annual interest rate, number of years to pay off the loan. First, you will calculate the monthly payment using a formula below. Then you will write a loop displaying the monthly payment breakdown: interest amount, principal applied to the loan, and the balance of the loan.
For a 1 year loan (12 monthly payments) for $10,000 at 7%, the payment breakdown looks like the following:
monthly payment = 865.27
payment:1 interest: 58.33 principal: 806.93 balance: 9193.07
HERE IS THE ISSUE ABOVE I CANT GET IT TO DISPLAY THE AMOUNT OF PAYMENTS FOR (x) MONTHS AND FOR IT TO DISPLAY THE REST OF THE INFO WITH IT.
import java.text.NumberFormat;
import java.util.Scanner;
public class MothlyPay {
public static double calculateMonthlyPayment(
int loanAmount, int termInYears, double interestRate) {
// Convert interest rate into a decimal
// eg. 6.5% = 0.065
interestRate /= 100.0;
// Monthly interest rate
// is the yearly rate divided by 12
double monthlyRate = interestRate / 12.0;
// The length of the term in months
// is the number of years times 12
int termInMonths = termInYears * 12;
// Calculate the monthly payment
// Typically this formula is provided so
// we won't go into the details
// The Math.pow() method is used calculate values raised to a power
double monthlyPayment =
(loanAmount*monthlyRate) /
(1-Math.pow(1+monthlyRate, -termInMonths));
return monthlyPayment;
}
public static void main(String[] args) {
// Scanner is a great class for getting
// console input from the user
Scanner scanner = new Scanner(System.in);
// Prompt user for details of loan
System.out.print("Enter loan amount: ");
int loanAmount = scanner.nextInt();
System.out.print("Enter loan term (in years): ");
int termInYears = scanner.nextInt();
System.out.print("Enter interest rate: ");
double interestRate = scanner.nextDouble();
// Display details of loan
double monthlyPayment = calculateMonthlyPayment(loanAmount, termInYears, interestRate);
double totalPayed = 0;
int month = 1;
double loanAmountRemaining;
// NumberFormat is useful for formatting numbers
// In our case we'll use it for
// formatting currency and percentage values
while(totalPayed <= loanAmount){
totalPayed = totalPayed + monthlyPayment;
double totalLoanAmount = loanAmount + interestRate;
loanAmountRemaining = totalLoanAmount - totalPayed;
month ++;
}
if(monthlyPayment > loanAmount)
totalPayed = totalPayed + loanAmountRemaining;
}
// Display details of the loan
//HERE IS THE ISSUE BELOW, I CANT GET IT TO DISPLAY THE AMOUNT OF PAYMENTS FOR (x) MONTHS AND FOR IT TO DISPLAY THE REST OF THE INFO WITH IT FOR THE FOLLOWING VARIABLE LISTED IN THE PRINTF STATEMENT.
System.out.printf("%9s %9s %9s %9s\n", "monthlypayment", "interestRate", "loanAmount", "loanAmountRemaining");
}
//When user put in the loan amount, interest rate, months, It needs display like the picture below.
Right now, you don't have your print statement in any specific method, meaning it won't be called. I would recommend putting it in your main method, and then running a loop to find and print your values.

Simple calculation not displaying correct value

I wrote a simple program that receives several inputs and it does a future investment calculation.
However, for some reason, when I enter the following values:
investment = 1
interest = 5
year = 1
I get Your future value is 65.34496113081846 when it should be 1.05.
import java.util.*;
public class futurevalue
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("This program will calculate your future investment value");
System.out.println("Enter investment amount: ");
double investment = sc.nextDouble();
System.out.println("Enter annual interest amount: ");
double interest = sc.nextDouble();
System.out.println("Enter number of years: ");
int year = sc.nextInt();
double futureValue = investment * (Math.pow(1 + interest, year*12));
System.out.println("Your future value is " + futureValue);
}
}
Found my mistake. I divided my interest twice.
You should divide your interest by 100.
How is the interest rate being entered? Should you not divide it by 100 before adding 1 inside Math.pow?
Example: Monthly interest = 1%, if you enter 1, your Math.pow would be Math.pow(1+1, year*12) which would be incorrect.
Yes, your main error is not dividing by 100 to convert from percents to proportion, but you have another error:
If you have an APR of 5% the formula you need to use to calculate a compounding monthly interest isn't 5%/12, it's
(0.05+1)^(1/12)-1
And then the return for that investment ends up being:
1 * ( (0.05+1)^(1/12)-1 +1 )^(1 * 12) =
1 * ( (0.05+1)^(1/12) )^(12) =
1 * ( 0.05+1 ) = 1.05
exactly.

Categories