dimanche 22 novembre 2015

C#: How to prevent all "if" statements from being executed consecutively

I have a C# program, using Visual Studio and the console template. All of my if statements are running consecutively. I want only one of the if statement's block scope to be evaluated if the conditional is true and for the others to be ignored when one is run.

Here is what I have:

Console.WriteLine("What is your age?");
string age = Console.ReadLine();

int ageInt;
Int32.TryParse(age, out ageInt);
if (ageInt >= 17)
{
    Console.WriteLine("You are rather young!");
    Console.WriteLine("Press any key to continue...");
    Console.ReadKey(true);
}
if (ageInt >= 18)
{
    Console.WriteLine("You are young, but technically an adult!");
    Console.WriteLine("Press any key to continue...");
    Console.ReadKey(true);
}
if (ageInt >= 21)
{
    Console.WriteLine("You are of legal drinking age! A semi-adult!");
    Console.WriteLine("Press any key to continue...");
    Console.ReadKey(true);
}
if (ageInt >= 30)
{
    Console.WriteLine("You are a true adult!");
    Console.WriteLine("Press any key to continue...");
    Console.ReadKey(true);
}

When it is supposed to show the message for each if statement, the console will just display the first if statement and then just run through each of the other if statements. Can anyone help me figure out how to change the code to do what I want?

Solution: All I needed to do was reverse the order of the if statements, and make every other if statement an "else if" statement like this:

if (ageInt == 100)
{
    Console.WriteLine("You are really old!");
    Console.WriteLine("Press any key to continue...");
    Console.ReadKey(true);
}
else if (ageInt >= 62)
{
    Console.WriteLine("You should retire!");
    Console.WriteLine("Press any key to continue...");
    Console.ReadKey(true);
}
else if (ageInt >= 30)
{
    Console.WriteLine("You are a true adult!");
    Console.WriteLine("Press any key to continue...");
    Console.ReadKey(true);
}
else if (ageInt >= 21)
{
    Console.WriteLine("You are of legal drinking age! A semi-adult!");
    Console.WriteLine("Press any key to continue...");
    Console.ReadKey(true);
}

Aucun commentaire:

Enregistrer un commentaire