Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Java present value calculator is not working

Tags:

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;
   }
}
like image 862
SteveDeFacto Avatar asked Sep 17 '26 10:09

SteveDeFacto


1 Answers

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.

like image 76
user2339071 Avatar answered Sep 20 '26 00:09

user2339071



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!