0

I am trying to run this code and eveything runs fine till the program has to write the answer from the question. i Keep getting a SystemIndexOutOfRangeException.

I dont seem to get this issue when i input the number 5, 6, 2 but anything else and i get this exception

static void Question1()
    {
        Console.WriteLine("Question 1");
        Console.WriteLine("----------------------------------------------------------------------");
        Console.WriteLine();

        int[] a = new int[] { 5, 7, 8, 3, 25, 10, 90 };
        int[] b = new int[] { 78, 6, 4087, 2, 2, 2, 6 };
        int[] c = new int[] { 2, 2, 3, 6, 5, 8, 90 };

        int aValue;
        int bValue;
        int cValue;

        Console.WriteLine("Array A = [{0}]", string.Join(", ", a));
        Console.WriteLine("Array B = [{0}]", string.Join(", ", b));
        Console.WriteLine("Array C = [{0}]", string.Join(", ", c));
        Console.WriteLine();

        Console.WriteLine("Enter a positional value of Array A");
        aValue = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine("Enter a positional value of Array B");
        bValue = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine("Enter a positional value of Array C");
        cValue = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine($"{a[aValue]} plus {b[bValue]} times {c[cValue]} = {a[aValue] + b[bValue] * c[cValue]} ");
        Console.WriteLine($"{a[aValue]} plus {b[bValue]} times {c[cValue]} = {(a[aValue] + b[bValue]) * c[cValue]} ");

        Console.ReadKey();
  • On what line are you getting the error message? – IceCode Aug 02 '22 at 20:16
  • 4
    Each of your arrays have 7 elements, so any index less than zero or greater than 6 will cause the exception. Arrays are zero based, so the first element will start at 0 and go to one less than it's length. You could add some error checking to your code to see if the user entered a number out of range and handle this so the exception is not thrown. – Ryan Wilson Aug 02 '22 at 20:17
  • Well, I agree with @RyanWilson, but if your code only works with your specific input called "5,6,2", then in that case you probably do not test with your compiled code. That's why I highly suggest to **Rebuild** your project. – ahmet gül Aug 03 '22 at 15:20

1 Answers1

0

Asking the user to input the value and then use it without validating that is between 0 and array.length is a bad practice

Change this:

aValue = Convert.ToInt32(Console.ReadLine());

To this

do {
   aValue = Convert.ToInt32(Console.ReadLine()) - 1;
   if ((aValue < 0) || (aValue > a.Length - 1)) {
       Console.WriteLine("That is not a valid position, try again");
   }
} while ((aValue < 0) || (aValue > a.Length - 1));
obnews
  • 602
  • 5
  • 13
Mauricio Gracia Gutierrez
  • 10,288
  • 6
  • 68
  • 99