简体   繁体   中英

Out of bounds with array index in C#

Basically I need to write a program that calculates the average rainfall per month over x years. I want it to ask the user for how many years then using for loops cycle through all the months and at the end calculating the average rainfall. But I'm getting an error when I run it

An unhandled exception of type 'System.IndexOutOfRangeException' occurred in Rainfall.exe

I think what's happening is that after the inside for loop finishes y is set to 12 which makes the array out of bounds, but I thought that once the outer array completes each loop that the y variable inside gets reset to 0.

Could anybody shed some light onto this please?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Rainfall
{
   class Program
   {
     static void Main(string[] args)
     {
        Console.WriteLine("This program will calculate the average amount of rainfall per month over the course of x years. ");
        Console.WriteLine();

        double years = 0;

        Console.WriteLine("Over how many years will this calculation take place?");

        years = int.Parse(Console.ReadLine());
        string[] months =  {"January", "February", "March", "April", "May", "June", "July", "August", "October", "November", "December" };

        double totalRainfall = 0;
        double monthRain = 0;
        double totalMonths = 0;
        double averageRainfall = 0;

        for (int x = 0; x < years; x++)
        {
            for(int y = 0; y < 12; y++)
            {
                Console.WriteLine("Enter the rainfall for the month of {0}", months[y]);

                monthRain = int.Parse(Console.ReadLine());

                totalRainfall = totalRainfall + monthRain;
            }
        }

        averageRainfall = totalRainfall / totalMonths;

        Console.WriteLine("The average rainfall per month is " + averageRainfall);
        Console.ReadLine();
     }
   }
}

In your for loop you expect there to be 12 months, but in your array of months you only have 11 months - September is missing. Add it and everything should be working fine:

string[] months =  {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM