Simple calculation not displaying correct value - java

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.

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

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.

How to implement a particular maths formula in 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

My methods aren't bringing the data along with it (beginner) [duplicate]

This question already has answers here:
Division in Java always results in zero (0)? [duplicate]
(3 answers)
Closed 8 years ago.
This is my first CS project ever. After creating my method, I ran the code to see if it works so far, everything works correctly but it does not actually do the math inside the method. Been working on this forever and can't find the bug. Any help would be great. Its due tomorrow lol.
public static void main(String[] args) {
int numberOfStudents = 0;
int total = 0;
int value = 0;
int creditHours;
double tuition;
int classesMissed;
System.out.println("Tuition Wasted Based on Student Absences and its effect on GPA.");
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the number of students to consider: ");
value = keyboard.nextInt();
while (value >= 5)
{
if (value > 5)
System.out.println("Number of students must be between 1 and 5");
System.out.print("Please re-enter a value number of students to consider: ");
value = keyboard.nextInt();
}
System.out.print("Enter the student ID for student 1: ");
value = keyboard.nextInt();
System.out.print("For how many credit hours is the student registered: ");
creditHours = keyboard.nextInt();
System.out.print("Enter the amount of the tuition for the semester: ");
tuition = keyboard.nextDouble();
System.out.print("Enter the average number of classes the student misses in a week: ");
classesMissed = keyboard.nextInt();
while (classesMissed > creditHours)
{
if (classesMissed > creditHours)
System.out.print("That is not possible, please re-enter the number of classes missed in a week: ");
classesMissed = keyboard.nextInt();
}
DetermineWastedTuition(creditHours, tuition, classesMissed);
}
public static void DetermineWastedTuition(int creditHours, double tuition, int classesMissed){
double weeklyTuition;
weeklyTuition = tuition / 10;
double weeklyTuitionWasted;
weeklyTuitionWasted = weeklyTuition *(classesMissed / creditHours);
double semesterWasted;
semesterWasted = weeklyTuitionWasted * 16;
System.out.println("Tuition money wasted each week is " + weeklyTuitionWasted);
System.out.println("Tuition money wasted each semester is " + semesterWasted);
}
With the sample output as:
Tuition Wasted Based on Student Absences and its effect on GPA.
Enter the number of students to consider: 1
Enter the student ID for student 1: 1234555
For how many credit hours is the student registered: 15
Enter the amount of the tuition for the semester: 7500
Enter the average number of classes the student misses in a week: 2
Tuition money wasted each week is 0.0
Tuition money wasted each semester is 0.0
The following calculation :
weeklyTuitionWasted = weeklyTuition * (classesMissed / creditHours);
would return 0.0 if classesMissed < creditHours, since you are dividing two int variables, and therefore the result will be an int.
Change it to :
weeklyTuitionWasted = weeklyTuition * ((double) classesMissed / creditHours);

Categories