简体   繁体   中英

c# populating array from user input, while loop, w/sentinel - IndexOutOfBounds error

I don't understand why I keep getting an IndexOutOfBounds exception. User is allowed to enter up to 10 numbers or sentinel value of -99. Error is thrown on 10th number. If I edited numbers.Length to numbers.Length -1, it wont throw the error, but it will only accept 9 numbers. Any idea?

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

namespace SomeProggy
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] numbers = new int[10];
            int x = 0;
            string entryString = "";
            int counter= -1;



            while (numbers[x] != 10 && counter < numbers.Length && entryString != "-99")
            {                            
                Write("Enter up to 10 numbers > ");
                entryString = ReadLine();
                numbers[x] = Convert.ToInt32(entryString);
                x++;
                counter++;
            }


        }
    }
}

Change your loop condition so that the array length is checked first:

while (counter < numbers.Length && numbers[x] != 10 && entryString != "-99")
{
     // ...
}

Otherwise when x increases to 10 it will go out of bounds while accessing numbers[x] . This will happen before the counter < numbers.Length check.

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