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 4 of 4

Thread: Help with Nested Loops

  1. #1
    Junior Member
    Join Date
    Oct 2010
    Posts
    28
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Help with Nested Loops

    Assignment:
    Average Rainfall
    Write a program that uses nested loops to collect data and calculate the average rainfall over a period of years. First the program should ask for the number of years. The outer loop will iterate once for each year. The inner loop will iterate 12 times, once for each month. Each iteration of the inner loop will ask the user for the inches of rainfall for that month. After all iterations, the program should display the number of months, the total inches of rainfall, and the average rainfall per month for the entire period.
    Input validation: Do not accept a number less than 1 for the number of years. Do not accept negative numbers for the monthly rainfall.

    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
     
    package averagerainfall;
    import java.util.Scanner;
     
    /**
     *
     * @author uuuuuuu
     */
    public class Main {
     
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            Scanner keyboard = new Scanner(System.in);
     
            int years;
            int months;
            double rainfall = 0;
            double totalRainfall = 0.0;
     
     
            System.out.println("Enter the number of years:");
            years = keyboard.nextInt();
     
            for(int count = 1; count<= years;count++)
            {
                for(months = 1; months<=12;months++)
                {
                    System.out.println("Enter inches of rainfall for month "
                            + months);
                        rainfall = keyboard.nextDouble();
                        totalRainfall += rainfall;;
                }
            System.out.println("Number of months: " + (months));
            System.out.println("Total inches of rainfall: " + totalRainfall);
            System.out.println("Average rainfall per month: " +
                    (totalRainfall/(years * months)));
        }
        }
    }

    In the code, where do I put [rainfall>0]?

    When I enter [1] for years, the output for number of months is [13], why isn't it [12], how do I fix it?

    When I put [2] for years, why doesn't the number of months accumulate; it should be [24] months not [12] and [12] (in my case, it is [13] and [13] because of coding problems.'

    I'll fix it the output decimal format into (##0.00) afterward.


  2. #2
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Help with Nested Loops

    It's possible that your value for months is lost after that for loop ends. It either will print out 12 when you say
    System.out.println("Number of months" + months); or it will claim it hasn't been initialized. I think it'll print out 12.

    Perhaps you should try putting the three lines of code within the brackets of the second for loop.

    Also, you only told it to go to twelve months per year. When the year ends, it starts over at month 1.

    1, 2, 3, 4, 5, 6,7, 8, 9, 10, 11, 12.

    I'm not sure about the format, but maybe %2d might work.

    No clue why it would be 13 months.

    Try

    for (int month = 1; month < 13; m++)

    instead of the the <=12 to see if that was causing it.

    Also, perhaps, maybe, your final 3 lines should be outside all of the for loops.

    Also, you could simply calculate it to do this:

    System.out.println("Number of months" + (years*12));

    However, I think that it's possibly still incrementing somehow when it gets to your last 3 statements.
    Last edited by javapenguin; October 23rd, 2010 at 03:01 PM.

  3. #3
    Junior Member
    Join Date
    Oct 2010
    Posts
    28
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Help with Nested Loops

    Quote Originally Posted by javapenguin View Post
    It's possible that your value for months is lost after that for loop ends. It either will print out 12 when you say
    System.out.println("Number of months" + months); or it will claim it hasn't been initialized. I think it'll print out 12.

    Perhaps you should try putting the three lines of code within the brackets of the second for loop.

    Also, you only told it to go to twelve months per year. When the year ends, it starts over at month 1.

    1, 2, 3, 4, 5, 6,7, 8, 9, 10, 11, 12.

    I'm not sure about the format, but maybe %2d might work.

    No clue why it would be 13 months.

    Try

    for (int month = 1; month < 13; m++)

    instead of the the <=12 to see if that was causing it.
    The assignment says that it should loop 12 times, once for each month. Thus, it should be months<=12.
    I think I'll have to put an "if-statement" in the inner loop; but what do I put as the boolean for it?
    The cause of it to appear as 13 months is because of the "months++"; an "if-statement" would resolve it but I'm not sure what boolean condition.
    And did what you told me, I put the 3 statements in the inner loop.

    As for the decimal format, I'll have to put
    import java.text.DecimalFormat;
    at the top of the code (under package) and then in the code:
    DecimalFormat fmt = new DecimalFormat("##0.00");
    and inside the output, I'll just have to add in
    fmt.format
    in front of the number that I want to use the format on.

  4. #4
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Help with Nested Loops

    import java.util.Scanner;
     
    /**
     *
     * @author uuuuuuu
     */
    public class Main {
     
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            Scanner keyboard = new Scanner(System.in);
     
            int years;
            int months;
            double rainfall = 0;
            double totalRainfall = 0.0;
     
     
            System.out.println("Enter the number of years:");
            years = keyboard.nextInt();
     
            for(int count = 1; count<= years;count++)
            {
                for(months = 1; months<=12;months++)
                {
                    System.out.println("Enter inches of rainfall for month "
                            + months);
                        rainfall = keyboard.nextDouble();
                        totalRainfall += rainfall;;
                }
     
        }
            System.out.println("Number of months: " + (years*12));
            System.out.println("Total inches of rainfall: " + totalRainfall);
            System.out.println("Average rainfall per month: " +
                    (totalRainfall/(years * 12)));
        }
    }

Similar Threads

  1. The defitition of nested loop
    By silentbang in forum Java Theory & Questions
    Replies: 2
    Last Post: October 16th, 2010, 02:38 PM
  2. Nested If Else Statement
    By jwill22 in forum What's Wrong With My Code?
    Replies: 6
    Last Post: October 6th, 2010, 02:46 PM
  3. nested loop
    By b109 in forum Java Theory & Questions
    Replies: 1
    Last Post: May 30th, 2010, 10:05 AM
  4. Nested try blocks
    By Ahmed. in forum Member Introductions
    Replies: 2
    Last Post: April 30th, 2010, 08:12 AM
  5. how do i draw a shape with nested loops?
    By Kilowog in forum Loops & Control Statements
    Replies: 1
    Last Post: September 25th, 2009, 12:14 AM