Reputation:
for (int loopCount = 0; loopCount < 9; loopCount++)
{
Console.WriteLine("Employee #" + (loopCount + 1) + " first name: ");
fullName[loopCount, 0] = Console.ReadLine().ToLower();
// first name
if (fullName[loopCount, 0].Length == 0)
{
giveError();
// nothing typed warning
}
Console.WriteLine("Employee #" + (loopCount + 1) + " second name: ");
fullName[0, loopCount] = Console.ReadLine().ToLower();
// second name
}
How do I return back to adding a first name if the user enters nothing without moving on to the next loop?
Upvotes: 0
Views: 83
Reputation: 25370
Assuming fullName is a string[9,2]
:
for (int loopCount = 0; loopCount < 9; loopCount++)
{
Console.WriteLine("Employee #" + (loopCount + 1) + " first name: ");
fullName[loopCount, 0] = Console.ReadLine().ToLower();
while(fullName[loopCount, 0].Length == 0)
{
Console.WriteLine("Bad Input, Retry");
fullName[loopCount, 0] = Console.ReadLine().ToLower();
}
}
It's worth the extra input line before the loop, so that if the loop is needed (i.e. bad input is received) you can supply a "bad input" message.
for your second name, you want fullName[loopCount,1]
, not fullName[0,loopCount]
Upvotes: 0
Reputation: 838
Wrap your logic around a do while loop:
string name = null;
do
{
// Read input from user
}
while(!IsLegal(name));
Upvotes: 4
Reputation: 609
Without changing your loop structure, you can add the following lines after giveError();
inside you if
statment:
loopcount--;
continue;
This will decrement your loopcount
, so you do not loose your place and will return your program to the top of the loop and then re-increment loopcount.
Upvotes: 0
Reputation: 7489
You can initialize an empty value before you ask for input, and then wrap the input code in a while loop that continues asking until a valid value is given:
string fullname = string.Empty;
while(string.IsNullOrEmpty(fullname))
{
fullname = Console.ReadLine().ToLower();
}
fullName[loopCount, 0] = fullname;
This way, if the user doesn't type anything, you'll just loop back and ask again.
Upvotes: 0