Reputation: 1
I updated my program. Here's what it does.
1. User inputs limit (must be a number)
2. If integer, stored in integer. Else, ask again. (already handled with if-else)
3. User inputs value (must be a number)
4. If integer, stored in integer array. Else, ask again. (this is the problem)
Console.Write("\n Enter limit on how many number(s): ");
string limit = Console.ReadLine();
int value;
if (int.TryParse(limit, out value))
{
int size = int.Parse(limit);
int[] a = new int[size];
for (int i = 0; i < size; i++)
{
//I need this part to filter first the input of user
Console.Write(" Value: ");
//If integer, I need it to be stored in the array
a[i] = Convert.ToInt32(Console.ReadLine());
/*string val = Console.ReadLine();
int detect;
if(!int.TryParse(Console.ReadLine(), out detect))
{
break;
}
else
{
}*/
}
int len = a.Length;
Program pj = new Program();
pj.programBExtension(a, len);
}
else
{
Console.Clear();
Console.WriteLine("\n You have entered an invalid value. You will be asked again to enter the limit.");
goto progB;
}
Upvotes: 0
Views: 3003
Reputation: 29006
use the same tricky TryParse
inside the Loop to;
for (int i = 0; i < size; i++)
{
if(!int.TryParse(Console.ReadLine(),out a[i])
{
break; // This is wrong input handle this
}
}
Upvotes: 1
Reputation: 3009
You are already filtering out strings which cannot be converted to integers so just use that value 'detect':
string b = Console.ReadLine();
int detect;
if (int.TryParse(b, out detect)) <-- Will filter out strings here
for (int i = 0; i < size; i++)
{
a[i] = detect;
}
int len = a.Length;
Program pj = new Program();
pj.programBExtension(a, len);
Upvotes: 0