Search code examples
javafor-loopnested-loopscalculated-columns

issue with nested for loop calculation


So I'm a (major) novice to java and i'm writing a simple program that prints out a table of monthly loan payments. I've got the formatting down but the nested for loop calculation is going over my head. I need to be able to deduct a monthly payment of $50 and figure in an interest rate I've prompted from the user from an initial loan of $1000.

Everything I've tried so far has either resulted in an infinite loop or the very first balance calculation being printed for all 12 months.

This is probably a very obvious question but any feedback would be much appreciated! For loops aren't very intuitive for me, and staring at this same bit of code has halted my progress!

( ..... )


//this method prompts the user to enter the annual interest rate and then prints it 
//along with the initial loan, monthly payment, and a simple loan payment table for 
//one year

private static void simpleLoanPaymentTable() {
  Scanner CONSOLE = new Scanner(System.in);
  double annualInterestRate;
  double initialLoan = 1000.0;
  double monthlyPayment = 50.0;

  System.out.println("Please enter the annual interest rate:");
  annualInterestRate = CONSOLE.nextDouble();
  double percentAnnualRate = (annualInterestRate/100);
  double percentMonthlyRate = (percentAnnualRate/12);
  System.out.println();
  System.out.println("The initial loan is $1000.0");
  System.out.println("The monthly payment is $50.0");
  System.out.println("The annual interest rate is " + annualInterestRate + "%");
  System.out.println();


  System.out.println("Simple Loan Payment Table For One Year");
  System.out.println();
  System.out.println(" Month  Balance");


  //create 12 rows for the months
  for(int row = 1; row <= 12; row++) { 
    //calculate monthly balance 
    for(double i = 0; i <= initialLoan; i++) {
      i = (initialLoan-monthlyPayment+(initialLoan*percentMonthlyRate));
      System.out.println(" " + row + "      " + i);
    }
  }
  System.out.println();
}

Solution

  • What do you think this is doing?

    for(double i = 0; i <= initialLoan; i++) {
      i = (initialLoan-monthlyPayment+(initialLoan*percentMonthlyRate));
      System.out.println(" " + row + "      " + i);
    }
    

    What is actually going on is that you are assigning the same value to i over and over again.

    Sit down with a pencil and paper and do the loan calculation by hand. Then convert the process you went through into code.

    Hint: based on what I think you ought to be doing, the inner loop should not be a for loop.