CSC 012

Introduction to Computer Science

 

Lab Exercise.   (p 104/4.3)  Write a program that computes the interest rate for an auto loan given the term of the loan (in months).  Loans for a term of 24 months or less have a rate of 0.9 percent; 36-month loans carry a rate of 2.9 percent, 48-month loans a rate of 4.9 percent, and 60-month loans a rate of 6.9 percent.

//File:    Rate.java
import CSLib.*;
public class Rate
{
    public static void main (String [] args)
    {
        //Input
        InputBox in = new InputBox();
        in.setPrompt ("What is the term of the loan? (12, 24, 36, 48, or 60 months)");
        int term = in.readInt();
       
       
        OutputBox out = new OutputBox();
   
        //Figure out the interest rate
        double rate = 0.0;
       
       /*
        if (term == 12 || term == 24)
        {
            rate = 0.9;
        }
        else if (term == 36)
        {
            rate = 2.9;
        }
        else if (term == 48)
        {
            rate = 4.9;
        }
        else if (term == 60)
        {
            rate = 6.9;
        }

        */
       
        //alternative to if-else
        switch (term)
        {
            case 12 :
            case 24 :             rate = 0.9;     break;
            case 36 :             rate = 2.9;     break;
            case 48    :          rate = 4.9;     break;
            case 60 :            rate = 6.9;     break;
            default :            out.println ("Must have term of 12, 24, 36, 48, or 60");
                                    Timer.pause (5000);
                                    System.exit (1);
        }


        //Output
       
        out.println ("With a term of " + term + " months, your interest rate is: " + rate
                            + "%.");
    }
}

Upon executing the Rate program, we get:

wpe45.jpg (7414 bytes)

wpe46.jpg (15912 bytes)

 

Back to Lecture