Simple Java present value calculator is not working - java

I have not used java before and I am confused as to why a simple present value calculator I wrote is not working. The present value formula returns a super small number for some reason? See if you can spot my error:
// Import all utilities
import java.text.DecimalFormat;
import java.util.*;
// Base class
public class Project2
{
// Main function
public static void main(String[] args)
{
// Define variables
double p = 0.0;
double f = 0.0;
double r = 0.0;
double n = 0.0;
String another = "Y";
// Create a currency format
DecimalFormat dollar = new DecimalFormat("#,###.00");
// Create a new instance of the scanner class
Scanner keyboard = new Scanner(System.in);
// Loop while another equals "Y"
while(another.equals("Y"))
{
// Get future value
System.out.println("Future value: ");
f = Double.parseDouble(keyboard.nextLine());
// Get annual interest rate
System.out.println("Annual interest rate: ");
r = Double.parseDouble(keyboard.nextLine());
// Get Number of years
System.out.println("Number of years: ");
n = Double.parseDouble(keyboard.nextLine());
// Run method to find present value and display result
p = presentValue(f, r, n);
System.out.println("Present value: $" + p );
// Ask if user wants to enter another
System.out.println("Enter another?(Y/N) ");
another = keyboard.nextLine().toUpperCase();
}
}
public static double presentValue(double f, double r, double n)
{
// Do math and return result
double p = f / Math.pow((1 + r), n);
return p;
}
}

Assuming you enter the R as % per annum i.e. for e.g. R = 4.3%, you would want to modify the function as :
double p = f / (Math.pow((1 + (r/100.0)), n));
return p;
If this is not what you would want, you might want to enter the value of R=4.3% p.a as
4.3/100 = 0.043 and not 4.3.

Instead of future value Please take an input for Principal.
Your PresentValue Calculation Function will be like this. Try this function, hope you will get your perfect result
public double presentValue(double principal, double yearlyRate, double termYears)
{
// Do math and return result
double pValue = principal * (((1- Math.pow(1 + yearlyRate, -termYears))/ yearlyRate));
return pValue;
}

Math.pow expects the first argument to be the base and the second the exponent. ( See The Math javadoc )
In your program the first argument is the power and the second is the base.
Change that to double p = f / Math.pow(n, (1 + r)); and I expect your program to run as expected

Your program works fine. I just tested it.
Future value:
100000
Annual interest rate:
0.4
Number of years:
20
Present value: $119.519642774552
Enter another?(Y/N)
Y
Future value:
100000
Annual interest rate:
40
Number of years:
20
Present value: $5.550381891760752E-28
Enter another?(Y/N)
You're entering the interest rate wrong probably.
If you want to enter an integer value, you can modify the formula:
double p = f / (Math.pow((1 + (r/100.0)), n));
This will result in:
Future value:
100000
Annual interest rate:
40
Number of years:
20
Present value: $119.519642774552
Enter another?(Y/N)

Related

using the NumberFormat import in System.out.format

I'm doing a program on compound interest for a school assignment. I tried using System.out.format(); and used money.format to format the variables investment, interest, and investTotal. I don't know why but it keeps on throwing me an error for
"Invalid value type 'String' for format specifier '%.2f', parameter 2, 3, and 4" I've been trying to figure this out for quite a while now and I still can't seem to find why it is.
-- A
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// SPLASH
// CONSTANT
// OBJECT
Scanner input = new Scanner(System.in);
NumberFormat money = NumberFormat.getCurrencyInstance();
// VARIABLES
double investment;
double investTotal;
double rate;
double intrest;
int year;
// INPUT
do
{
System.out.print("Enter yearly investment (min $100.00 deposit): ");
investment = input.nextDouble();
}
while (investment < 100);
do
{
System.out.print("Enter intrest rate (%): ");
rate = input.nextDouble()/100;
}
while (rate <= 0);
do
{
System.out.print("Enter number of years: ");
year = input.nextInt();
}
while (year <= 0 || year > 15);
// PROCESSING
investTotal = investment;
for (int perYear = 1; perYear <= year; perYear++)
{
intrest = investTotal*rate;
investTotal = (investment+intrest);
System.out.format("%2s | %.2f | %.2f | %.2f\n", perYear, money.format(investment), money.format(intrest), money.format(investTotal));
investTotal = investTotal + investment;
}
// OUTPUT
}
}
getCurrencyInstance returns a String and therefor can't be formatted using %.2f.
You better look how NumberFormat works:
https://docs.oracle.com/javase/7/docs/api/java/text/NumberFormat.html
As you can see, the result of the formatting is a String, when you are using String.format with %.2f you should enter a number e.g:
System.out.format("%2s | %.2f\n", 1.001, 1.005);
I'm not sure what are you trying to get using the NumberFormat, if you classify I will be able to help you further with this question.

issues with java and printf and decimals

Code:
import java.util.Scanner;
public class sdusti00lab1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
double AA = 8.25;
double CA = 6.50;
double ACP = 9.00;
double CPC = 6.25;
int numA, numC;
double numSP, numLP;
Scanner keys = new Scanner(System.in);
System.out.print(" enter number of adults ");
numA = keys.nextInt();
System.out.println(" enter number of children ");
numC = keys.nextInt();
System.out.println(" enter number of small popcorn");
numSP = keys.nextDouble();
System.out.println(" enter number of large popcorn");
numLP = keys.nextDouble();
double AAddPrice = (numA*AA);
double CAddPrice = (numC*CA);
double ACPT = ((ACP*.094)*AA);
double CPCT = ((CPC*.094)*CA);
double SPTax = (ACP*.094);
double LPTax = (CPC*.094);
System.out.println("Adult admission "+"\t"+numA + "\t$" + AAddPrice);
System.out.println("Child admission "+"\t"+numC + "\t$" + CAddPrice);
System.out.println("Adult popcorn "+"\t\t"+ACP + "\t$" + ACPT);
System.out.println("Child popcorn "+"\t\t"+CPC + "\t$" + CPCT);
System.out.println("Tax "+"\t\t\t$"+ (SPTax + LPTax));
System.out.println("Total "+"\t\t\t$"+(AAddPrice+CAddPrice+CPCT+ACPT) );
}
}
I need to change the last 6 lines of code to produce a decimal that stops at the number second to the decimal, but I just don't know how to do that.
Use System.out.printf or System.out.format to do this. Use %.2f for printing upto two decimal point.
System.out.printf("Adult admission \t%d\t$%.2f%n", numA, AAddPrice);
There are various ways to turn numbers (float, double, ..) into formatted Strings. Oracle has a nice overview worth studying.
The important aspect to understand here: that process works by you
A) specifying a format that describes how your output should look like
B) you calling a formatter with that format and the numbers to format

Create a program that prompt user fa a floating point(double) Fahrenheit and then return equal value in Celsius

import java.util.*;
class TempConver {
public static void main(String[] args) {
double temperature;
Scanner in = new Scanner(System.in);
System.out.printf("Enter Fahrenheit Temperature: ");
temperature = in.nextInt();
temperature = (temperature - 32) * 5 / 9;
System.out.printf("Censius Temperatre is = " + temperature);
}
}
I've to write program using information given below.
output formatting - "printf()" instead of print() or println()
Do While loops - repeat a question until a user gives you a valid response
Scanner.HasNextDouble() - method to ascertain whether or not the next item the scanner is about to read works as a double data type
Please help me how to write output in 2 place decimal using do while loop. !!
You have all the answers you need in the hints.
Do While loops - repeat a question until a user gives you a valid response And Scanner.hasNextDouble() - method to ascertain whether or not the next item the scanner is about to read works as a double data type
Here you are telling the user, while the input is not a double, then execute the code. Which will be asking the user for input until you get a double
while (!in.hasNextDouble()) {
// code here
}
To round to two decimals you can use Math.round() to round a value to the nearest integer, and multiply temperature by 100 then divide by 100.
int round = (int) Math.round(temperature*100);
temperature = round / 100.0;
Full code:
public static void main(String[] args) {
double temperature;
Scanner in = new Scanner(System.in);
System.out.printf("Enter Fahrenheit Temperature: ");
// As long as it is not a double ask for another input
while (!in.hasNextDouble()) {
System.out.printf("Please enter a valid number:");
in.next();
}
temperature = in.nextDouble();
temperature = (temperature - 32) * 5 / 9;
// Use only 2 decimals
int round = (int) Math.round(temperature*100);
temperature = round / 100.0;
System.out.printf("Censius Temperatre is = " + temperature);
}

monthly payment calculator

I have some code which I find to keep giving me a dividing by 0 error.
It is suppose to calculate the monthly payment amount!
import java.io.*;
public class Bert
{
public static void main(String[] args)throws IOException
{
//Declaring Variables
int price, downpayment, tradeIn, months,loanAmt, interest;
double annualInterest, payment;
String custName, inputPrice,inputDownPayment,inputTradeIn,inputMonths, inputAnnualInterest;
BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
//Get Input from User
System.out.println("What is your name? ");
custName = dataIn.readLine();
System.out.print("What is the price of the car? ");
inputPrice = dataIn.readLine();
System.out.print("What is the downpayment? ");
inputDownPayment = dataIn.readLine();
System.out.print("What is the trade-in value? ");
inputTradeIn = dataIn.readLine();
System.out.print("For how many months is the loan? ");
inputMonths = dataIn.readLine();
System.out.print("What is the decimal interest rate? ");
inputAnnualInterest = dataIn.readLine();
//Conversions
price = Integer.parseInt(inputPrice);
downpayment = Integer.parseInt(inputDownPayment);
tradeIn = Integer.parseInt(inputTradeIn);
months = Integer.parseInt(inputMonths);
annualInterest = Double.parseDouble(inputAnnualInterest);
interest =(int)annualInterest/12;
loanAmt = price-downpayment-tradeIn;
//payment = loanAmt*interest/a-(1+interest)
payment=(loanAmt/((1/interest)-(1/(interest*Math.pow(1+interest,-months)))));
//Output
System.out.print("The monthly payment for " + custName + " is $");
System.out.println(payment);
// figures out monthly payment amount!!!
}
}
the problem occurs when attempting to set the payment variable.
i don't understand why it keeps coming up with dividing by 0 error.
You have declared your variables as Int so 1/interest and 1/(interest*Math.pow(1+interest,-months)) will return 0. Change the type of your variables to float or double.
One suggestion to you, is that you should learn to "backwards slice" your code.
This means that when you see that you're getting a DivideByZeroException you should look at your code, and say, "why could this happen?"
In your case, let's look at this:
payment=(loanAmt/((1/interest)-(1/(interest*Math.pow(1+interest,-months)))));
So, now, Math.pow will never return anything zero (as it's a power), so it must be the case that interestis zero. Let's find out why:
interest =(int)annualInterest/12;
So now, integer division in Java truncates. This means that if you have .5 it will be cut off, and turned into zero. (Similarly, 1.3 will be truncated to 0).
So now:
annualInterest = Double.parseDouble(inputAnnualInterest);
This implies that you are passing in something that gets parsed to a value that is less than 12. If it were greater than 12 then you would get something else.
However, you might just be passing in an invalid string, for example, passing in "hello2.0" won't work!
This will be rounding always to 0. So it is trowing exception.
(1/interest)-(1/(interest*Math.pow(1+interest,-months)))));
Use float type instead of int. Learn how they works.
package computeloan;
import java.util.Scanner;
public class ComputeLoan {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print(" Enter Yearly Interest Rate : ");
double annualIntersetRate = input.nextDouble();
double monthlyIntersetRate = annualIntersetRate / 1200;
System.out.print(" Enter Number of years : ");
int numberOfYears = input.nextInt();
// Enter loan amount
System.out.print(" Enter Loan Amount : ");
double loanAmount = input.nextDouble();
double monthlyPayment = loanAmount * monthlyIntersetRate /(1-1/Math.pow(1+monthlyIntersetRate,numberOfYears*12 ));
double totalPayment = monthlyPayment * numberOfYears * 12;
//Calculate monthlyPaymeent and totalPayment
System.out.println(" The Monthly Payment Is : " +(int)(monthlyPayment*100) /100.0);
System.out.println(" The Total Payment Is : " +(int)(totalPayment*100) /100.0 );
}
}

Taking a users input in a library class and making sure it is positive

Here are my two java files that I am working with. The problem I am having is getting the getPosNum method (highlighted below) to take the number the user inputs and see if that number is positive rather than doing what is doing right now, which is:
jGRASP exec: java Prog12
OUTPUT: First Investment
INPUT: Please enter a positive number: -5000.00
INPUT: ERROR: -5000.0 is not positive; try again: -3000.00
Rather than getting it to say something like this:
jGRASP exec: java Prog12
OUTPUT: First Investment
INPUT: Enter the first principal amount: -5000.00
INPUT: ERROR: -5000.0 is not positive; try again: -3000.00
How can I fix this problem and make it read correctly? Am I making sense?
public class Finance
{
public static double getPosNum (String prompt)
{
double num;
num = Input.readDouble("Please enter a positive number: ");
while (num <= 0.0)
num = Input.readDouble("ERROR: " + num +
" is not positive; try again: ");
Output.showValue("You entered ", num);
return num;
} // method getPosNum
public static void outFinances (double prin, double rate, double years, double fv)
{
Output.showMessage("The original amount invested was $" + prin + ",\nand the annual interest rate was set at " + rate + "%.\nIt has been " + years + " years since the investment was made,\nand the future value of the investment after that many years is $" + fv + ".");
} // method outFinances
public static double futureValue (double prin, double rate, double years)
{
double FV, P, r, n;
P = prin;
r = rate;
n = years;
FV = P * Math.pow((1 + (r / 100)),(n));
return FV;
} // method outFinances
} // class Finance
// File: Prog12.java
// CS200 Lab 12 Main
// Author: Ryan Pech
// Created: February 19, 2011
public class Prog12
{
public static void main (String [] args)
{
double p, r, y, fv;
Output.showMessage("First Investment");
p = Finance.getPosNum("Enter the first principal amount: ");
r = Finance.getPosNum("Enter the first interest rate: ");
y = Finance.getPosNum("Enter the first number of years: ");
fv = Finance.futureValue(p, r, y);
Finance.outFinances(p, r, y, fv);
Output.showMessage("Second Investment");
p = Finance.getPosNum("Enter the second principal amount: ");
r = Finance.getPosNum("Enter the second interest rate: ");
y = Finance.getPosNum("Enter the second number of years: ");
fv = Finance.futureValue(p, r, y);
Finance.outFinances(p, r, y, fv);
} // method main
} // class Prog12
// File: Finance.java
// CS200 Lab 12
// Author: Ryan Pech
// Created: February 19, 2011
Your getPostNum() accepts a parameter called prompt, but you never use that variable in that method at all. Instead of hardcoding Please enter a positive number:, substitute that string with that prompt variable, like this:-
Change...
num = Input.readDouble("Please enter a positive number: ");
... to...
num = Input.readDouble(prompt);
It should be obvious that it's printing "Please enter a positive number: " because you explicitly told it to in the getPosNum() method.
Using
num = Input.readDouble(prompt)
will solve your problem. A better way to go about this is to restrict printing to your main() method and use getPosNum() for input only. This way you know explicitly what you are printing every time. Something like
System.out.println("Enter the first principle amount.");
num = Input.readDouble();
and then perform some negative number checks.

Categories

Resources