Exercise 1

  1. Write a program that calculates the compounding value of an investment I with a given interest rate R and a given duration in years D.
    Here is an example of input and output of this program:
    Enter investment amount: 1500
    Enter interest rate in %: 4.5
    Enter number of years: 5
    
    OUTPUT
    
    Investment=$1500.0
    Rate=4.5%
    Number of Years=5
    Your final Amount : $1869.27
    

    Solution

    public class exer1 {
              /* program that calculates the compounding value of an investment I with a given interest rate R and a given
         duration in years D.  */
    
    
    	public static void main(String args[]) {
        /* Variables */
        
        float investmentAmount;
        float interestRate;
        float finalAmount;
        int nbYears;
        int i;
    
    	/* Program statements go here. */
    	
    		/*Reading input*/
    		System.out.print("Enter investment amount: ");
    		investmentAmount=Keyboard.in.readFloat().floatValue();		
    		System.out.print("Enter interest rate in %: ");
    		interestRate=Keyboard.in.readFloat().floatValue();		
    		System.out.print("Enter number of years: ");
    		nbYears=Keyboard.in.readInteger().intValue();
    		
    		/*Calculating the compounding investment*/
    	        finalAmount=investmentAmount;
    		for(i=0;i<nbYears;i++) {
    		    finalAmount = finalAmount + (finalAmount*interestRate/100);
    		    
    		}		
    		/*making sure there are only two digits after decimal point*/
    		finalAmount=((float)Math.round(finalAmount*100))/100;	
    		investmentAmount=((float)Math.round(investmentAmount*100))/100;
    		
    		/*printing the output*/	
    		System.out.println("Investment=$" +investmentAmount);
    		System.out.println("Rate=" +interestRate+"%");
    		System.out.println("Number of Years=" +nbYears);
    		System.out.println("Your final Amount : $" + finalAmount);
    	}
    }
    

  2. Change the previous program such that the investment is either compounded every year, every 6 months, or every month, based on a given parameter P.
    Here is an example of input and output of this program:
    Enter investment amount: 1500
    Enter interest rate in %: 4.5
    Enter number of years: 5
    Interest Compounded: (1)Yearly, (2)Every 6 months, (3)Monthly:6
    (1)Yearly, (2)Every 6 months, (3)Monthly:abc
    (1)Yearly, (2)Every 6 months, (3)Monthly:33
    (1)Yearly, (2)Every 6 months, (3)Monthly:3
    
    OUTPUT
    
    Investment=$1500.0
    Rate=4.5%
    Number of Years=5
    Period: Monthly
    Your final Amount : $1877.69     
         

    Solution

    public class exer1 {
              /* program that calculates the compounding value of an investment I with a given interest rate R and a given
         duration in years D.  */
    
    
    	public static void main(String args[]) {
        /* Variables */
        
        float investmentAmount;
        float interestRate;
        float finalAmount;
        int nbYears;
        int nbPeriods;
        float intRate;
        String label;
        int i;
        char mySelection;
    
    	/* Program statements go here. */
    	
    		/*Reading input*/
    		System.out.print("Enter investment amount: ");
    		investmentAmount=Keyboard.in.readFloat().floatValue();		
    		System.out.print("Enter interest rate in %: ");
    		interestRate=Keyboard.in.readFloat().floatValue();		
    		System.out.print("Enter number of years: ");
    		nbYears=Keyboard.in.readInteger().intValue();
    		System.out.print("Interest Compounded:");
    
                    mySelection=question("(1)Yearly, (2)Every 6 months, (3)Monthly:","123");
    
    		/*Determining the number of periods, 
    		  the interest rate to use, and the label for period*/
    		switch(mySelection) {
    			case '1': nbPeriods=nbYears;
    					  intRate = interestRate;
    					  label="Yearly";
    					  break;
    			case '2': nbPeriods=nbYears*2;
    					  intRate = interestRate/2;
    					  label="Every 6 months";
    					  break;
    			case '3': nbPeriods=nbYears*12;
    					  intRate = interestRate/12;
    					  label="Monthly";
    					  break;
    			default:  nbPeriods=0;
    					  intRate = 0f;
    					  label="Unknown";
    		}
    
    		/*Calculating the compounding investment*/
    	        finalAmount=investmentAmount;
    		for(i=0;i<nbPeriods;i++) {
    		    finalAmount = finalAmount + (finalAmount*intRate/100);
    		    
    		}		
    		/*making sure there are only two digits after decimal point*/
    		finalAmount=((float)Math.round(finalAmount*100))/100;	
    		investmentAmount=((float)Math.round(investmentAmount*100))/100;
    		
    		/*printing the output*/	
    		System.out.println("Investment=$" +investmentAmount);
    		System.out.println("Rate=" +interestRate+"%");
    		System.out.println("Number of Years=" +nbYears);
    		System.out.println("Period:" +label);
    		System.out.println("Your final Amount : $" + finalAmount);
    	}
    
    	public static char question(String theQuestion, String validChoice) {
    
    		char theChoice;
    		String userInput;
    
    		do{
    			System.out.print(theQuestion);
    			userInput=Keyboard.in.readString();
    			theChoice = userInput.charAt(0);
    		} while (validChoice.indexOf(theChoice)==-1 || userInput.length()!=1);
    		return theChoice;
    	}
    }
    

  3. Change the previous program such that the processing of the investment value is done in a method of a class Investment invoked many times in the main program for different values of I, R, D, and P.

    Solution

    public class exer1 {
              /* program that calculates the compounding value of an investment I with a given interest rate R and a given
         duration in years D.  */
    
    
    	public static void main(String args[]) {
        /* Variables */
        
        float investmentAmount;
        float interestRate;
        float finalAmount;
        int nbYears;
        Investment myInvestment;
    
    
    	/* Program statements go here. */
    		do {
    			/*Reading input*/
    			System.out.println("\nEnter amount 0 to quit.");
    			System.out.print("Enter investment amount: ");
    			investmentAmount=Keyboard.in.readFloat().floatValue();
    			if (investmentAmount !=0f) { 		
    				System.out.print("Enter interest rate in %: ");
    				interestRate=Keyboard.in.readFloat().floatValue();		
    				System.out.print("Enter number of years: ");
    				nbYears=Keyboard.in.readInteger().intValue();
    				System.out.print("Interest Compounded:");
    				myInvestment=new Investment(investmentAmount,interestRate,nbYears);
    				/*asking for periodicity and assigning a ratio*/
            		myInvestment.question();
            		/*printing the result for an investment*/
            		myInvestment.display();
    			}	
    		} while (investmentAmount!=0f);
    
    	}
    
    }
    
    public class Investment {
    
    /*Instance Variables*/
    
    private float investment;
    private float yearlyRate;
    private int years;
    private int ratio;
    
    	/*constructor Investment*/
    	public Investment(float sum, float percent, int duration){
    		this.investment=sum;
    		this.yearlyRate=percent;
    		this.years=duration;
    		this.ratio=1;
    	}
    
    	/*calculates the final amount based on rate and duration*/
    	public float calculate(){
    	
    		int i;
    		float finalAmount=this.investment;
    
    		for (i=0; i<(this.years*this.ratio);i++) 
    			finalAmount=finalAmount+finalAmount*(this.yearlyRate/this.ratio)/100;
    
    		return finalAmount;
    	}
    
    	/*dislays investment info*/
    	public void display(){
    
    		float finalAmount;
    		finalAmount=this.calculate();
    
    		/*making sure there are only two digits after decimal point*/
    		finalAmount=((float)Math.round(finalAmount*100))/100;	
    
    		System.out.println("Investment=$" +this.investment);
    		System.out.println("Rate=" +this.yearlyRate+"%");
    		System.out.println("Number of Years=" +this.years);
    		System.out.println("Period:" + this.periodicity());
    		System.out.println("Your final Amount : $" + finalAmount);
    	}
    	
    	/*generates a label for periodicity*/
    	private String periodicity(){
    		switch(this.ratio) {
    			case 1: return "Yearly";
    			case 2: return "Every 6 months";
    			case 3: return "Quaterly";
    			case 12:return "Monthly";
    			default: return "Unknown";
    		}
    	}
    	
    	/*asks a question to determine periodicity*/
    	public void question() {
    		String theQuestion = "(1)Yearly, (2)Every 6 months, (3)Monthly:";
    		String validChoice = "123";
    		char theChoice;
    		String userInput;
    
    		do{
    			System.out.print(theQuestion);
    			userInput=Keyboard.in.readString();
    			theChoice = userInput.charAt(0);
    		} while (validChoice.indexOf(theChoice)==-1 || userInput.length()!=1);
    
    		switch(theChoice) {
    			case '1': this.ratio=1;
    					  break;
    			case '2': this.ratio=2;
    					  break;
    			case '3': this.ratio=12;
    					  break;
    		}
    	}
    
    }
    

  4. Change the previous program such that it displays the increases in the investment value after each year period.
    Here is an example of input and output of this program:
    Enter amount 0 to quit.
    Enter investment amount: 1500
    Enter interest rate in %: 4.5
    Enter number of years: 5
    Interest Compounded:(1)Yearly, (2)Every 6 months, (3)Monthly:1
    
    Year	Ratio   Investment      Increase        Amount End of Year
    1       	4.5     	1500.0          	67.5             1567.5
    2       	4.5     	1567.5          	70.54           1638.04
    3       	4.5     	1638.04         	73.71           1711.75
    4       	4.5     	1711.75         	77.03           1788.78
    5       	4.5     	1788.78         	80.49           1869.27
    
    Enter amount 0 to quit.
    Enter investment amount: 1500
    Enter interest rate in %: 4.5
    Enter number of years: 5
    Interest Compounded:(1)Yearly, (2)Every 6 months, (3)Monthly:2
    
    Year	Ratio   Investment      Increase        Amount End of Year
    1 	4.5	1500.0		33.75           1533.75
    1	4.5	1533.75       	34.51           1568.26
    2	4.5	1568.26        	35.29           1603.55
    2	4.5	1603.55        	36.08           1639.63
    3	4.5	1639.63        	36.89           1676.52
    3	4.5	1676.52        	37.72           1714.24
    4	4.5	1714.24        	38.57           1752.81
    4	4.5	1752.81        	39.44           1792.25
    5	4.5	1792.25        	40.32           1832.57
    5	4.5	1832.57        	41.24           1873.81
    

    Solution

    Add the followintg method in the Investment class:

         /*calculates the final amount based on rate and duration*/
         public float displayPerYear(){
    	
    	int i;
    	float finalAmount=this.investment;
    	int currentYear=0;
    	float initial = this.investment;
    	float finalSum;
    	float increase;
    
    	System.out.println("\nYear\tRatio\tInvestment\tIncrease\tAmount End of Year");		
    		
    	for (i=0; i<(this.years*this.ratio);i++){ 
    		if (this.ratio==1 || (this.ratio==2&&i%2==0)|| (this.ratio==12 && i%12==0))  {
    			currentYear+=1;
    		}
    		initial=(float)Math.round(finalAmount*100)/100;
    
    		finalAmount=finalAmount+finalAmount*(this.yearlyRate/this.ratio)/100;
    		finalSum=(float)Math.round(finalAmount*100)/100;
    		increase=(float)Math.round((finalSum-initial)*100)/100;
    		System.out.print(currentYear+"\t"+this.yearlyRate+"\t");
    		System.out.print(initial+"\t\t"+increase+"\t\t");
    		System.out.println(finalSum);		
    	}
    	return finalAmount;
         }
    
    
    In the main method, replace the statement myInvestment.display(); by the statement  myInvestment.displayPerYear();.
    
    
  5. Can you add in the class Investment a method that given values for R, D, P, and a final sum S, will calculated the necessary initial investment I?

    Solution