Reputation: 43
In C# I declared an array of float in main()
float[] notas = new float[8];
Called the method and passed the array by reference also in main()
PopulateArray(ref notas);
Here's the implementation of the method PopulateArray(ref float[] arr1)
static void PopulateArray(ref float[] arr1)
{
bool vakid;
for (int i = 0; i < arr1.Length; i++)
{
do
{
do
{
Console.Write($"Insira nota {i + 1} ==>");
vakid = float.TryParse(Console.ReadLine(), out arr1[i]);
if ((arr1[i] > 20.0) || (arr1[i] < 0.0))
{
Console.Write("\n\n\t\tAs notas só vão de 0 a 20\n\nPrima uma tecla para continuar");
Console.ReadKey();
}
Console.Clear();
}while (!((arr1[i] <= 20) && (arr1[i] >= 0)));
} while (!vakid);
}
}
Used two loops, one to assure that the value inputed is between [0, 20] and another to ensure that whatever input is a decimal number (float). Before this implementation, the array notas was of integer and everything was working just fine, only integers were allowed and also in between the interval of [0, 20]. When I decided to change the type of data to float, whenever I type a decimal number (i.e. 3.0) it doesn't go through the outter loop, like if I were typing a character other than a number, much in the same way as when I type a letter. So how can I type decimal numbers to store in my array? Ty
Upvotes: 1
Views: 161
Reputation: 974
I propose this alternative implementation :
static void PopulateArray(float[] arr1)
{
for (int i = 1; i <= arr1.Length; i++)
{
float nota;
Console.Write($"Insira nota {i} ==> \n");
while(! float.TryParse(Console.ReadLine(), out nota) || nota > 20.0f || nota < 0 )
{
// Bad input message
Console.Write("\n\n\t\tAs notas só vão de 0 a 20\n\nPrima uma tecla para continuar");
}
arr1[i] = nota;
}
}
Note that you don't need to pass the array by reference. It's a reference type, so a copy of the reference is passed and the method can work on it.
Upvotes: 3
Reputation: 39142
Culture issue aside (decimal separator of .
vs ,
), I'd get rid of one of the do loops like this:
static void PopulateArray(float[] arr1)
{
bool vakid;
for (int i = 0; i < arr1.Length; i++)
{
do
{
Console.Write($"Insira nota {i + 1} ==>");
vakid = float.TryParse(Console.ReadLine(), out arr1[i]);
if (vakid)
{
if ((arr1[i] > 20.0) || (arr1[i] < 0.0))
{
vakid = false;
Console.Write("\n\n\t\tAs notas só vão de 0 a 20\n\nPrima uma tecla para continuar");
Console.ReadKey();
}
}
else
{
Console.Write("\n\n\t\tInvalid Entry\n\nPrima uma tecla para continuar");
Console.ReadKey();
}
Console.Clear();
} while (!vakid);
}
}
Upvotes: 2