Gustavo,
In your code, you create an array with the size of x, which in the case is zero:
int x = 0;
double[] dados = new double[x];
With this, you have an array of size zero, so when trying to access the index of the same:
dados[x] = double.Parse(Console.ReadLine());
You have the mistake that System.Indexoutofrangeexception
You can change the code to have a fixed size array by assigning a size to the array:
double[] dados = new double[10]; //Agora o array tem o tamanho de dez
And in the while condition, have a new check, to avoid typing more than the array supports, an example would be like this:
if (x < dados.Length)
{
Console.WriteLine("Digite Y para continuar digitando valores:");
if (Console.ReadKey().Key != ConsoleKey.Y || x >= dados.Length)
{
stop = false;
}
}
else
{
stop = false;
}
In the end, your code would look something like this:
using System;
class ArrayTeste {
static void Main()
{
Boolean stop = true;
int x = 0;
double[] dados = new double[3];
do
{
Console.WriteLine("\nDigite um numero:");
dados[x] = double.Parse(Console.ReadLine());
x += 1;
if (x < dados.Length)
{
Console.WriteLine("Digite Y para continuar digitando valores:");
if (Console.ReadKey().Key != ConsoleKey.Y)
{
stop = false;
}
}
else
{
stop = false;
}
} while (stop);
Console.WriteLine("\nDados recebidos");
for(int i = 0; i < dados.Length; i++)
{
Console.WriteLine(dados[i]);
}
Console.ReadKey();
}
}
Note: The do/while would be easily exchanged for a FOR, since you
knows the size of the array.
Maybe, you are interested in lists, see your code using list, it is much simpler... And with foreach:
using System;
using System.Collections.Generic;
class ListTeste {
static void Main()
{
Boolean stop = true;
List<double> dados = new List<double>();
do
{
Console.WriteLine("\nDigite um numero:");
dados.Add(double.Parse(Console.ReadLine()));
Console.WriteLine("Digite Y para continuar digitando valores:");
if (Console.ReadKey().Key != ConsoleKey.Y)
{
stop = false;
}
} while (stop);
Console.WriteLine("\nDados recebidos");
foreach(double valor in dados)
{
Console.WriteLine(valor);
}
Console.ReadKey();
}
}
The list does not have a predefined size, so I can keep the while while you have the patience to type numbers.
Finally, you can create the matrix based on an informed number:
int tamanho = int.Parse(Console.ReadLine());
double[] dados = new double[tamanho];
Console.WriteLine(dados.Length);
just a comment, it’s not strange to start the code with a variable
stop = true
? already starting to stop? andwhile (stop)
It’s also strange... if the variable were calledcontinuar
or something similar (may not becontinue
) would be better– Ricardo Pontual
x = 0 or your array has no position or positions? How will you save values without space!
– novic