Home > Enterprise >  Java: How to make my nested for loop stop after it has completed its loop
Java: How to make my nested for loop stop after it has completed its loop

Time:10-26

My assigment](https://i.stack.imgur.com/dmCPJ.png)

I am pretty new to this so sorry if i am not clear. My code works so far for one year (12months), however when i want to find the average rainfall for two years (24months), it finds it for 48months.

Not sure how to fix this, or where the problem is situated

import java.util.Scanner;

public class AverageRainfall {

    public static void main(String[] args) {
        Scanner kb = new Scanner(System.in);
        
        System.out.println("How many years did it rain? ");

        int years = kb.nextInt();

        
        for (int i = 1; i <= years; i  ){
            for(int j = 1; j <= (years * 12); j  ){
                System.out.println("How many inches of rain this month?");
                totalRain  = kb.nextInt();
                
                System.out.println("Month: "   j);
                System.out.println(totalRain   " Inches of rain!" );
            }
    }
        System.out.println("The average rainfall over the period of: "   years   "years is:"   totalRain/(12*years)   "Inches");
        
    }
    
}

I tried changing things inside my for loop conditions but i can't figure it out

CodePudding user response:

Try using the break statement at which condition you want to break. In that case, you can easily come out of the loop. You already looping per year so you do not need to multiply the year again in the next loop. Original : for(int j = 1; j <= (years * 12); j ) Changed: for(int j = 1; j <= 12; j )

Here is some ref: https://www.programiz.com/java-programming/break-statement

import java.util.Scanner;

public class AverageRainfall {

    public static void main(String[] args) {
        Scanner kb = new Scanner(System.in);
        
        System.out.println("How many years did it rain? ");

        int years = kb.nextInt();
        int totalRain = 0;

        
        for (int i = 1; i <= years; i  ){
            for(int j = 1; j <= 12; j  ){
                System.out.println("How many inches of rain this month?");
                totalRain  = kb.nextInt();
                
                System.out.println("Month: "   j);
                System.out.println(totalRain   " Inches of rain!" );
            }
    }
        System.out.println("The average rainfall over the period of: "   years   "years is:"   totalRain/(12*years)   "Inches");
        
    }
    
}

CodePudding user response:

The main problem in your code is that you are looping over 12 * years for every year (if you have 2 years, you will loop twice over 24 months). You should use the inner loop only for looping over each month, or just use one loop that is 12 * years

Also please take note that it is good practise to close the Scanner using .close() method.

If you are new I'd suggest you to always use significative names for your variables, for example you could rename "kb" to "scanner", because when the code is longer, the reader loses context of what "kb" is, in any case you should not shorten words and at least use "keyboard" instead

You also need to add some spaces when concatenating string with variables, otherwise you will see things like "period of 9years"

Here's your code, I've taken profit of the structure stated in the assignment and added some messages to improve user experience and information on what he is typing in any moment

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    
    System.out.println("How many years did it rain? ");

    int years = scanner.nextInt();
    int totalRain = 0;

    for (int i = 1; i <= years; i  ){
         System.out.println("Lets go with year "   i   ":");
         
        for(int j = 1; j <= 12; j  ){
            System.out.println("How many inches of rain in month "   j   " ?");
            totalRain  = scanner.nextInt();
            
            System.out.println(totalRain   " inches of rain in total!" );
        }
    }
    
     System.out.println("The average rainfall over the period of: "   years   " years is: "   totalRain/(12*years)   " inches.");
    
     scanner.close();
}
  • Related