Need to answered in Java Moneynext Moneytoday1rate The grow
Need to answered in Java.
Moneynext = Moneytoday(1+rate)
The growth formula per year is simply: Assume you withdraw money from the account after it grows (you cannot withdraw more than the account has!). Find out how long it takes to reach the desired amount of money (if it is reachable at all).
Example 1 (user input is italic):
Initial investment? 1000
Yearly growth rate? 0.1
Yearly withdraw amount? 50
Desired balance? 1000000
Years: 80
Balance at end: 1.0247e+06
Amount withdrawn over period: 4000
Example 2 (user input is italic):
Initial investment? 100
Yearly growth rate? 0.1
Yearly withdraw amount? 99999999
Desired balance? 1000000
Years: 1
Balance at end: 0
Amount withdrawn over period: 110
Example 3 (user input is italic):
Initial investment? 1000
Yearly growth rate? 0.1
Yearly withdraw amount? 20
Desired balance? 1000000
Years: 18
Balance at end: 0
Amount withdrawn over period: 340.114
Example 4 (user input is italic):
Initial investment? 5000
Yearly growth rate? 0.16
Yearly withdraw amount? 0
Desired balance? 1000000
Years: 36
Balance at end: 1.04582e+06
Amount withdrawn over period: 0
Solution
import java.util.Scanner;
public class Driver
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println(\"Initial investment? \");
Double investment = sc.nextDouble();
System.out.println(\"Yearly growth rate? \");
Double rate = sc.nextDouble();
System.out.println(\"Yearly withdraw amount? \");
Double withdraw = sc.nextDouble();
System.out.println(\"Desired balance? \");
Double desiredBalance = sc.nextDouble();
Double moneyToday, moneyNext, totalWithdrawn = 0.0, endBalance =0.0;
int years = 0;
moneyToday = investment;
while(true)
{
years++;
moneyNext = (1+rate)*moneyToday;
if(moneyNext > withdraw)
{
moneyNext = moneyNext - withdraw;
totalWithdrawn = totalWithdrawn + withdraw;
}
else
{
totalWithdrawn = totalWithdrawn + moneyNext;
break;
}
endBalance = endBalance + moneyNext;
moneyToday = moneyNext;
if(endBalance > desiredBalance)
break;
if(endBalance < 0)
{
endBalance = 0.0;
break;
}
}
System.out.println(\"Years: \" + years + \"\ Balance at end: \" + endBalance + \"\ Amount withdrawn over period: \" + totalWithdrawn);
}
}


