Java Reference
In-Depth Information
retirementFund
variable, so the new amount is used in the next calculation. Because the
fundAmount
is a
double
, you also need to change the type of
retirementFund
to a
double
as well. If you do this,
you'll also see an error pop up for the
monthlyPension
variable, since it uses
retirementFund
in its
calculation. Change this to a
double
type also. You can, of course, remove the first print statement
now that you know the method is calculating correctly. You should end up with something like this.
public class Errors {
public static void main(String[] args) {
int age = 30;
double retirementFund = 10000;
int yearsInRetirement = 20;
String name = "David Johnson";
for (int i = age; i <= 65; i++){
retirementFund = recalculate(retirementFund,0.1);
}
double monthlyPension = retirementFund/yearsInRetirement/12;
System.out.println(name + " will have $" + monthlyPension
+ " per month for retirement.");
}
public static double recalculate(double fundAmount, double rate){
return fundAmount*(1+rate);
}
}
The output now, which should make you feel a little more optimistic about potential retirement,
is
David Johnson will have $1288.0283555362819 per month for retirement.
It is also
possible to reformat the string representation of that
double
to a more common two‐decimal place
number using a
DecimalFormat
class. That implementation isn't important for this chapter, but you
might find it interesting.
import java.text.DecimalFormat;
public class Errors {
public static void main(String[] args) {
int age = 30;
double retirementFund = 10000;
int yearsInRetirement = 20;
String name = "David Johnson";
for (int i = age; i <= 65; i++){
retirementFund = recalculate(retirementFund,0.1);
}
double monthlyPension = retirementFund/yearsInRetirement/12;
// create a decimal format with two decimal points
DecimalFormat df = new DecimalFormat ("0.##");
// use the df.format() method to format the double
System.out.println(name + " will have $" + df.format(monthlyPension)
+ " per month for retirement.");
Search WWH ::
Custom Search