0

First, I initialize an ArrayList to my code then add each input by the user. I manage to add a data and show but after doing so it throws an exception of OutOfRange and I don't see any reason why.

I already asked about something like this but it was to check the array has value stored yet Link to my first question. But the problem I encountered now is something this exception

static ArrayList fName = new ArrayList();
static ArrayList cNumber = new ArrayList();

public static void createContact()
{
    Console.Write("\nEnter your full name: ");
    fullName = Console.ReadLine();
    fName.Add(fullName);

    Console.Write("\nEnter your contact number: ");
    contactNumber = Console.ReadLine();
    cNumber.Add(contactNumber);
}

public static void displayContact()
{
    if (fName.Count == 0 && cNumber.Count == 0)
    {
        Console.WriteLine("No Data Yet!");
    }

    else if (fName.Count > 0 && cNumber.Count > 0)
    {
        for (int j = 0; j < numbers.Length; j++)
        {
            Console.WriteLine(numbers[j] + ". " + fName[j] + " - " + cNumber[j]);
        }
    }

    else if (fName.Count <= 10 && cNumber.Count <= 10)
    {
        Console.WriteLine("Maximum data acquired! Terminating program...");
    }
}

The output goes something like this:

Output 1

Output 2

8
  • I'm not sure what numbers represents, but evidently it has more items than fName or cNumber. I recommend learning to debug. You can step through your code with the debugger and inspect individual variables to see what data they hold, etc. Commented Apr 28, 2021 at 9:52
  • numbers represents as the numbered list for my arrays that being input by the user Commented Apr 28, 2021 at 9:54
  • Does numbers contain more items than fName or cNumber? Commented Apr 28, 2021 at 9:55
  • Sorry, I am really new in doing arraylist. I've no idea on what I'm doing, I just do what my mind thinks is right but I got it all wrong on that exception. Commented Apr 28, 2021 at 9:56
  • OK, imagine numbers contains 2 items, so your loop (for (int j = 0; j < numbers.Length; j++)) visits item at index 0 first, and then item at index 1 next. fName, on the other hand, only contains 1 item. So on the first loop, you are able to access the item at index 0. On the second loop, you ask for the item at index 1 but that doesn't exist. That's why you get this error. Commented Apr 28, 2021 at 9:57

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.