Dalton Gray Dalton Gray - 2 months ago 10
C# Question

Is there a way to make a loop with multiple conditions? c#

I made a simple program that asks the user for their name, then a number that is 1 or 2 and then writes their name and number to the console.

The problem I am having is that I don't know how to make it so that the user can only enter the numbers 1 or 2 in a single loop (I am assuming there is something obvious I am missing).

Code:

string strName;
string strNumber;
int intNumber;

Console.WriteLine("What is your name?");
strName = Console.ReadLine();

Console.WriteLine("Please enter a number (1 or 2)");
strNumber = Console.ReadLine();
bool test = int.TryParse(strNumber, out intNumber);

while (intNumber >2)

{
Console.WriteLine("Please enter a number (1 or 2)");
strNumber = Console.ReadLine();
int.TryParse(strNumber, out intNumber);
}
while (intNumber < 1)

{
Console.WriteLine("Please enter a number (1 or 2)");
strNumber = Console.ReadLine();
int.TryParse(strNumber, out intNumber);
}
while (test == false)

{
Console.WriteLine("Please enter a number (1 or 2)");
strNumber = Console.ReadLine();
int.TryParse(strNumber, out intNumber);
}


Console.WriteLine("Welcome, your name is "+ strName+ " your number is " + intNumber);
Console.ReadKey();


As you can see from the code above I have 3 separate loops, which creates a problem since they run from top to bottom and once they have been passed they no longer loop, so the user could enter: 10, f and then 7 and the program would be OK with that.

If there is another more simple way of doing what I want could you tell me please.

-Thanks

Answer

Do you mean something like this?

int response = 0;

while (response != 1 && response != 2)
{
    Console.WriteLine("Please enter a number (1 or 2)");
    var strNumber = Console.ReadLine();
    int intNumber;
    if (int.TryParse(strNumber.Trim(), out intNumber))
    {
        response = intNumber;
    }
}