Home > Software engineering >  How would the following values in the nested loop print horizontally before newline for original loo
How would the following values in the nested loop print horizontally before newline for original loo

Time:10-03

I'm working on learning printf statements and I can't seem to figure out how to get the full number of values outputted by the nested for loop (j aka payments) before dropping to the next line and reading the next set of values associated with the first loop iterating. Here's where I'm at....

Public class Printer {

    public static void main(String[] args) {

        // nested loop: first loop show the interest rate from starting to ending
        for (double i=4.000; i<=6.000; i =0.250){ // prints interest rates from starting to ending in increments of .25
            System.out.printf("%.3f", i); // %.3f print 3 decimal places and %n prints the new line
            for (int j=15; j<=30; j =5){ // prints the payments calculations from the startingTerm to the endingTerm
                double payments = paymentCalculator(j, i); // throw the increasing payment scale and increasing term scale into the paymentCalculator to show increasing payments
                System.out.printf(".2f %n", payments); // 8 positions wide for field (right justified) with 2 decimal places attached
            }
        }
    }

    /*public static double paymentCalculator(int years, double annualRate){
        annualRate = annualRate / 100; // convert percentage rate to decimal
        // convert annual values to monthly values
        double mir = annualRate / 12; // monthly interest rate (mir)
        double mtp = years * 12; // months to pay (mtp)

        // calculate annuityFactor
        double numerator = (Math.pow((1 mir), mtp) * mir); // numerator
        double denominator = (Math.pow((1 mir), mtp) - 1); // denominator
        double annuityFactor = numerator / denominator;

        // payment
        double payment = 100000 * annuityFactor; //calculate payment

        return payment;
    }*/
}

my printed console

CodePudding user response:

You get multiple lines because you have a %n at the end of your string.

Just use System.out.printf(".2f ", payments);

And after the nested loop, print a new line

  •  Tags:  
  • java
  • Related