Input Logic Not Resolving As Anticipated

Viewed 44

I'm trying to figure out my code isn't working.

I'm trying to input an age, and assign a color to it based on it like I've show below, but my input always comes out green if its above 12.

Console.WriteLine("input your age: ");
int age = int.Parse(Console.ReadLine());

if (age<= 12)
{
    Console.WriteLine("color: white");
}
else if (age>= 13)
{
    Console.WriteLine("color: green");
}
else if (age >= 19)
{
    Console.WriteLine("color: red");
}
else if (age >= 26)
{
    Console.WriteLine("color: blue");
}
else
{
    Console.WriteLine("invalid age");
}

Console.ReadLine();
3 Answers

Numbers that should have given the output of red and blue are also larger than 13, so that condition evaluates to true. You're missing the counterpart of the range - for green, the age shouldn't just be greater or equal than 13, it should also be less than 19. The same issue exists for the blue condition:

if (age <= 12)
{
    Console.WriteLine("color: white");
}
else if (age >= 13 && age < 19) // Here!
{
    Console.WriteLine("color: green");
}
else if (age >= 19 && age < 26) // And here!
{
    Console.WriteLine("color: red");
}
else if (age >= 26)
{
    Console.WriteLine("color: blue");
}

Here in your second condition you have written if the age >= 13 then it should print color: green. So, in your case any number you will enter above 12 will be satisfied within this condition and you will always get color: green as output.

If your number is greater than 13 it automatically returns green and then ends at this point. You can change the sequence beginning with the greatest and then ending with the smallest.

Related