0

I keep getting an error and I have no idea why, someone please tell me why this doesn't work. It not only does it give me an error but it fails to store the second input into userInput[1].

string[] name = new string[4];
double[] bankAccount = new double[4];;

int x;
for (x = 0; x <= name.Length; x++)
  {
    Console.Write("Please enter first Name and their bank status: ");
    string[] userInput = Console.ReadLine().Split();
    name[x] = userInput[0];
    bankAccount[x] = double.Parse(userInput[1]);
    Console.WriteLine(userInput[0], userInput[1]);
  }
AsthaUndefined
  • 1,111
  • 1
  • 11
  • 24
Brian Naranjo
  • 314
  • 2
  • 5
  • 13
  • 5
    `x < name.Length` not `<=` – juharr Nov 06 '18 at 03:21
  • Thank you, it worked. I am curious as to why? If I wanted to run 5 times I assumed it would go from 0 to 4, what am I not getting? – Brian Naranjo Nov 06 '18 at 03:27
  • @BrianNaranjo you set the length of the array to 4, you can't go to the 5th index – saarrrr Nov 06 '18 at 03:28
  • Possible duplicate of [What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?](https://stackoverflow.com/questions/20940979/what-is-an-indexoutofrangeexception-argumentoutofrangeexception-and-how-do-i-f) – Tetsuya Yamamoto Nov 06 '18 at 03:34

1 Answers1

2

As you probably know, Arrays always start counting elements from index 0.

string[] stringArray = { "Hello", "There" };
Console.WriteLine(stringArray.length); // this will output 2, because there are two elements
Console.WriteLine(stringArray[0]); // this will output hello, and [1] would output there

Whats happening?

for (x = 0; x <= name.Length; x++)

In your code, you are attempting to loop through the array for any value that is either equal to, or less than the length. Why doesn't this work? Simple, arrays count at 0. When you want to access an element within an array, you need to start by counting the first element at 0.

It's also important to note that while accessing an element will start counting from 0, the elements amount itself won't count from 0. That's why stringArray.length returns 2, while stringArray[2] throws an ArrayOutOfBounds.

To fix this issue, simply change your <= condition check to <.

juharr
  • 31,741
  • 4
  • 58
  • 93
Frontear
  • 1,150
  • 12
  • 25
  • 2
    Arrays always start counting elements by 1? – AsthaUndefined Nov 06 '18 at 03:30
  • Oh thanks, good explanation. I was confused cause I thought setting the array to length 4 would actually give me 5 elements instead of 4. – Brian Naranjo Nov 06 '18 at 03:31
  • 1
    You should edit this so that it's at least consistent. *Arrays always start counting elements by 1* is simply wrong, and later you write *accessing an element will start counting from 0*. That makes it confusing, especially to new coders who can't figure out which one of them is correct. – Ken White Nov 06 '18 at 03:38
  • My bad, I've seemingly mixed things up – Frontear Nov 06 '18 at 17:59