Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 8 of 8

Thread: Loop Help

  1. #1
    Junior Member
    Join Date
    Feb 2012
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Loop Help

    I am working on a project for school and I am not sure the proper way to loop the program. I have to do separate interest rates and and term years. I have built those two vars into arrays but can't seem to get it to work right. I am sure I am using them wring and should just be looping the entire payment call, but not sure how to do it.

     
    import java.text.*; //To use text formatting
    import java.util.Scanner; //To use the scanner
     
    public class Wk1MortgagePaymentCalculator {
     
        NumberFormat currency = NumberFormat.getCurrencyInstance(); //Currancy Format
        DecimalFormat intRate = new DecimalFormat("##.00"); //Interest Format
     
        /**
         * The following loads the static variables for the program.
         */
     
        double payment = 0.0;
        double rate = 0.0;
        double principal = 200000.0;
        double[] annualInterest = {0.0535,0.0550,0.0575};
        int[] years = {7,15,30};
        int months = 0;
        int lineCount = 20;
     
        public static void main(String[] args) {
            Wk1MortgagePaymentCalculator MP = new 
                    Wk1MortgagePaymentCalculator(args);
     
        }
     
         public Wk1MortgagePaymentCalculator(String[] args) {
            if (args.length == 3) {
                principal = Double.parseDouble(args[0]);
                for (int i=0; i< annualInterest.length; i++)
                annualInterest[i] = Double.parseDouble(args[1])/100;
                for (int i=0; i< years.length; i++)
                years[i] = Integer.parseInt(args[2]);
                print();
            }
            else 
            {
                showUsage();
            }
     
        }
     
         /**
          * The following calculates the monthly payment.
          */
     
        public void calculatePayment(){
            for (int i=0; i< annualInterest.length; i++)
            rate = annualInterest[i] / 12;
            for (int i=0; i< years.length; i++)
            months = years[i] * 12;
            payment = (principal * rate) 
                    / (1 - Math.pow(1/ (1 + rate), months));
     
        }
     
        /**
         * The following prints out information about the program, the static 
         * fields, and calls the amortization.
         */
     
        public void print(){
            System.out.println("The principal is " + currency.format(principal));
            for (int i=0; i< annualInterest.length; i++)
            System.out.println("The annual interest rate is " + 
                    intRate.format(annualInterest[i] * 100) +"%");
            for (int i=0; i< years.length; i++)
            System.out.println("The term is " + years[i] + " years");
            System.out.println("Your monthly payment is " + currency.format(payment));
            //showAmortization(); // Calls the amortization method
        }
     
        public void showUsage() {
            calculatePayment(); // Calls the calculate payment method
            System.out.println("Usage: Calculate Mortgage Payment Amount ");
            System.out.println("\nFor example: $200,000 Mortgage loan amount, "
                    + "5.75% interest for a 30 year term ");
            System.out.println("\nThe Following is your output based on the "
                    + "hardcoded amount: \n");
            print();
            System.exit(0); // Controlled exit
     
        }
     
        /**
         *  Prints out the amortization table for the loan.
         */
     
        public void showAmortization() {
            double pmtInterest = 0.0;
            double pmtPrincipl = 0.0;
            double pmtBalance = 0.0;
     
     
            System.out.println("\nPmt#:\tPrincipalPmt\tInterestPmt\tBalance");
            System.out.println("====\t===========\t===========\t=======");
     
            Scanner s = new Scanner(System.in);
     
            for ( int i = 1; i <= months; ++i )
            {
                pmtInterest = principal * rate; // Payment to intrest
                pmtPrincipl = payment - pmtInterest; // Payment to princapl
                pmtBalance = principal - pmtPrincipl; 
     
                System.out.println( "#" + i
    			+ "\tP=" + currency.format(pmtPrincipl)
    			+ "\tI=" + currency.format(pmtInterest)
    			+ (pmtInterest < 10 ? "\t\tB=" : "\tB=")  // Tab adjustment
    			+ currency.format(pmtBalance) );
     
                principal -= pmtPrincipl; // Reduce the payment-to-principal
     
                if ( (i % lineCount) == 0 ) {
                    String input = s.nextLine(); // Pauses for an enter
     
                }
     
            }
     
            s.close(); // Closes the scanner call
     
        }
     
     
    }


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,910
    Thanks
    55
    Thanked 2,351 Times in 2,322 Posts

    Default Re: Loop Help

    You need to properly format your code to make it easier to read and understand.
    Statements within for statements should be indented and enclosed in {}s

    Can you explain what your problem with looping is? Explain what the loop is supposed to do on each time around.

  3. #3
    Junior Member
    Join Date
    Feb 2012
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Loop Help

    Norm,

    I have arrays built for the interest rate and term of a loan (annualInterest & years). What I believe I need to do but not sure how is to loop calculatePayment, print, and showAmortization to go through each index of the two arrays.

    Don

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,910
    Thanks
    55
    Thanked 2,351 Times in 2,322 Posts

    Default Re: Loop Help

    Can you explain what you want to do?
    For any loan I would assume that there is one interest rate and one term of years.

    Pick an interest rate and then compute the values for all the terms of years.
    Then pick the next interest rate and compute the values for all the terms of years.
    Looks like too loops> one to pick the intertst rates and then to use the years

  5. #5
    Junior Member
    Join Date
    Feb 2012
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Loop Help

    I do not need to calculate a given interest rate for all terms. I need to do index 0 of each var, index 1 and then index 2.

    Once the program runs against annualInterest[0] & years[0], I need it to move to annualInterest[1] & years[1].

    Here is the running code without some loops I was playing with.

     
    import java.text.*; //To use text formatting
    import java.util.Scanner; //To use the scanner
     
    public class Wk1MortgagePaymentCalculator {
     
        NumberFormat currency = NumberFormat.getCurrencyInstance(); //Currancy Format
        DecimalFormat intRate = new DecimalFormat("##.00"); //Interest Format
     
        /**
         * The following loads the static variables for the program.
         */
     
        double payment = 0.0;
        double rate = 0.0;
        double principal = 200000.0;
        double[] annualInterest = {0.0535,0.0550,0.0575};
        int[] years = {7,15,30};
        int months = 0;
        int lineCount = 20;
     
        public static void main(String[] args) {
            Wk1MortgagePaymentCalculator MP = new 
                    Wk1MortgagePaymentCalculator(args);
     
        }
     
         public Wk1MortgagePaymentCalculator(String[] args) {
            if (args.length == 3) {
                principal = Double.parseDouble(args[0]);
                annualInterest[0] = Double.parseDouble(args[1])/100;
                years[0] = Integer.parseInt(args[2]);
                print();
            }
            else 
            {
                showUsage();
            }
     
        }
     
         /**
          * The following calculates the monthly payment.
          */
     
        public void calculatePayment(){
            rate = annualInterest[0] / 12;
            months = years[0] * 12;
            payment = (principal * rate) 
                    / (1 - Math.pow(1/ (1 + rate), months));
     
        }
     
        /**
         * The following prints out information about the program, the static 
         * fields, and calls the amortization.
         */
     
        public void print(){
            System.out.println("The principal is " + currency.format(principal));
            System.out.println("The annual interest rate is " + 
                    intRate.format(annualInterest[0] * 100) +"%");
            System.out.println("The term is " + years[0] + " years");
            System.out.println("Your monthly payment is " + currency.format(payment));
            showAmortization(); // Calls the amortization method
        }
     
        public void showUsage() {
            calculatePayment(); // Calls the calculate payment method
            System.out.println("Usage: Calculate Mortgage Payment Amount ");
            System.out.println("\nFor example: $200,000 Mortgage loan amount, "
                    + "5.75% interest for a 30 year term ");
            System.out.println("\nThe Following is your output based on the "
                    + "hardcoded amount: \n");
            print();
            System.exit(0); // Controlled exit
     
        }
     
        /**
         *  Prints out the amortization table for the loan.
         */
     
        public void showAmortization() {
            double pmtInterest = 0.0;
            double pmtPrincipl = 0.0;
            double pmtBalance = 0.0;
     
     
            System.out.println("\nPmt#:\tPrincipalPmt\tInterestPmt\tBalance");
            System.out.println("====\t===========\t===========\t=======");
     
            Scanner s = new Scanner(System.in);
     
            for ( int i = 1; i <= months; ++i )
            {
                pmtInterest = principal * rate; // Payment to intrest
                pmtPrincipl = payment - pmtInterest; // Payment to princapl
                pmtBalance = principal - pmtPrincipl; 
     
                System.out.println( "#" + i
    			+ "\tP=" + currency.format(pmtPrincipl)
    			+ "\tI=" + currency.format(pmtInterest)
    			+ (pmtInterest < 10 ? "\t\tB=" : "\tB=")  // Tab adjustment
    			+ currency.format(pmtBalance) );
     
                principal -= pmtPrincipl; // Reduce the payment-to-principal
     
                if ( (i % lineCount) == 0 ) {
                    String input = s.nextLine(); // Pauses for an enter
     
                }
     
            }
     
            s.close(); // Closes the scanner call
     
        }
     
     
    }

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,910
    Thanks
    55
    Thanked 2,351 Times in 2,322 Posts

    Default Re: Loop Help

    Are you sure that you don't need to calculate the values for all three years for each of the interest rates? That would make for 9 different calculations.
    You think you only need to do it for 3. That would mean you only need one loop

  7. #7
    Junior Member
    Join Date
    Feb 2012
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Loop Help

    I am sure I only need three calculations. I am running short on turning this in. How would I get it to loop the entire program to run through each of the array index's?

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,910
    Thanks
    55
    Thanked 2,351 Times in 2,322 Posts

    Default Re: Loop Help

    Where does the code currently use elements from the arrays? Can that code be put in a loop that iterates through all the elements in the arrays instead of just using the one hardcoded [0]th element?

Similar Threads

  1. Converting a while loop to a for loop and a for loop to a while loop.
    By awesom in forum Loops & Control Statements
    Replies: 3
    Last Post: February 26th, 2012, 08:57 PM
  2. For loop; Problems with my for loop
    By mingleth in forum Loops & Control Statements
    Replies: 5
    Last Post: November 16th, 2011, 07:24 PM
  3. [SOLVED] My while loop has run into an infinite loop...?
    By kari4848 in forum Loops & Control Statements
    Replies: 3
    Last Post: March 1st, 2011, 12:05 PM
  4. for loop and while loop problems
    By Pulse_Irl in forum Loops & Control Statements
    Replies: 4
    Last Post: May 3rd, 2010, 03:09 AM
  5. hi. i want to rewrite this do loop into a while loop.
    By etidd in forum Loops & Control Statements
    Replies: 3
    Last Post: January 26th, 2010, 05:27 PM