Home > Mobile >  How to put the user input in a array and go through the array in C#
How to put the user input in a array and go through the array in C#

Time:11-23

Im making a code that gets the user input and put then in descending order, but i need help in this part, to put the user input into a array, the much input the user make, only stopping when '-1' is typed. Here is the code:

 int []vet = new int[]{};

for(int i = 0; i != -1;i  )
{
    Console.WriteLine("digite os valores");
    int input = int.Parse(Console.ReadLine());
    vet[i] = input;

}

This code generates this error: "Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array."

CodePudding user response:

I noticed 2 major problems with your code.

A. you used an array for a dynamic sized list. B. you used a for loop for an unknown amount of iterations.

The solution for problem A is, use a List<int> from the namespace System.Collections.Generic (important to import that)

For problem B you should use a while loop and check when an input variable is equals to -1, then close the loop.

CodePudding user response:

Try something like this:

List<int> vet = new List<int>();
int Response = 0;

Console.WriteLine("digite os valores");
Response = int.Parse(Console.ReadLine());
vet.Add(Response);

while (Response != -1)
{
     Console.WriteLine("digite os valores");
     Response = int.Parse(Console.ReadLine());
     vet.Add(Response);
}

CodePudding user response:

Thanks! It worked.I improve my mistakes and changed the code and i understood where i have made the mistake. Now it is working!

  • Related