j doe j doe - 3 months ago 7
C# Question

Why is my else passing through

So basically for class we are using an if else where the user inputs a string and if that string is correct we assign a value to a specific variable. My code seems to be fine, but for some reason when I run it and test using the exact strings the program runs through the if and goes to the else, and prints the else even though our if is true. Here is my code: (I initialized all of the variables at the beginning and did not include them here.

value = Console.ReadLine();

if (value == "ATX")
{
number1 = 3;
}
if (value == "XTS")
{
number1 = 34;
}
if (value == "CTS")
{
number1 = 2;
}
else
{
number1 = 0;
}

Console.WriteLine(number1);


So basically if i enter ATX or XTS I get number1 = 0, but if I do the CTS then number1 = 2. What is going wrong here?

Answer

Actually when you pass "ATX" or "XTS", your code will set the value of number1 variable to "3" or "34".But you are overwriting the value of number1 variable again with your last if-else block.

Use else if throughout

if (value == "ATX")
{
    number1 = 3;
}
else if (value == "XTS")
{
    number1 = 34;
}
else if (value == "CTS")
{
    number1 = 2;
}
else
{
    number1 = 0;
}
Console.WriteLine(number1);