Mr incognito
Mr incognito

Reputation: 1

How to fix If statement issue in c#?

First things first, I am an absolute beginner to c# so excuse me for any dumb mistakes I have done. currently, I am making a "banking system" as my beginner project. I am getting a frustrating error with entering a key.

           var input = Convert.ToString(Console.ReadKey());

           if (input == "E") {
               Console.WriteLine("English has been selected");
           }
           if (input == "A")
           {
               Console.WriteLine("تم اختيار اللغة العربية");
           }
           else {
               Console.WriteLine("Error!");
           }

if I input E or A the console only displays the Else condition instead of the two if conditions. side note: vscode doesn't show any errors relating to this.

Upvotes: 0

Views: 156

Answers (3)

topsail
topsail

Reputation: 3119

In your code you are using ReadKey() - but you must be sure to use it properly. It's not quite as simple as say Python input() but C#'s ReadKey() does a good job once you understand it.

First, and most importantly, you need to know that ReadKey() does not just return a letter (like 'a', or 'b'), and it does not even return a numeric key code (like 9 or 10). Instead, it returns something called a ConsoleKeyInfo. Technically, it is a struct, but you can just think of it as "information about the key pressed".

Second, because your goal is to know what key was pressed and specifically if it was an A or E, you can get the Key property from the ConsoleKeyInfo. But once again, we are not getting a letter (like 'a' or 'b'), or strictly speaking an integer (like 9 or 10) - . The Key we get is an Enum or more specifically a ConsoleKey Enum. So at this point we can either check the enum value directly, or convert it to a string representation and check it against a string value (such as "A" or "E").

Now, all of this can seem overkill for a tiny little program - but overall it provides a lot of benefit for writing safe and reliable programs. To compare it with something similar, it is like using a FileInfo object to represent a file, rather than just a using string for a filepath. But I do encourage you to read the docs referenced below because when you understand how to make use of documentation (and debugging tools) you have what you need to figure out most of this on your own!

tldr;

ReadKey() returns ConsoleKeyInfo struct, which we can use to get a Key property. Since the Key property returns an Enum, not a character or a string, we either check the value of the enum directly, or take one more step of calling ToString() on the ConsoleKeyEnum to convert it to a "letter" or "key" in string form. Additionally, the ConsoleKeyInfo class exposes a KeyChar property that may be used instead.

Reference: https://learn.microsoft.com/en-us/dotnet/api/system.console.readkey?view=net-6.0

sample revised code

var input = Console.ReadKey();

if (input.Key.ToString() == "E")
{
    Console.WriteLine("English has been selected");
}
else if (input.Key.ToString() == "A")
{
    Console.WriteLine("تم اختيار اللغة العربية");
}
else
{
    Console.WriteLine("Error!");
}

Because we are working with Enums, it is really simpler and safest to use them in the comparisons directly:

var input = Console.ReadKey();

if (input.Key == ConsoleKey.E)
{
    Console.WriteLine("English has been selected");
}
else if (input.Key == ConsoleKey.A)
{
    Console.WriteLine("تم اختيار اللغة العربية");
}
else
{
    Console.WriteLine("Error!");
}

Additionally we have the option to use the KeyChar property (this one does, however, return characters, not strings, and case matters - so we can get 'A', or 'a' depending on if shift is used or not).

var input = Console.ReadKey();

if (input.KeyChar == 'E' || input.KeyChar == 'e')
{
    Console.WriteLine("English has been selected");
}
else if (input.KeyChar == 'A' || input.KeyChar == 'a')
{
    Console.WriteLine("تم اختيار اللغة العربية");
}
else
{
    Console.WriteLine("Error!");
}

Upvotes: 4

YungDeiza
YungDeiza

Reputation: 4530

The simplest solution is to simply use Console.ReadLine() instead of Console.ReadKey(). This will require the user to press enter after they have selected wither A or E but this is more user friendly when selecting an option as it gives you the chance to confirm your choice.

var input = Convert.ToString(Console.ReadLine());

if (string.Equals(input, "E", StringComparison.InvariantCultureIgnoreCase))
{
    Console.WriteLine("English has been selected");
}
else if (string.Equals(input, "A", StringComparison.InvariantCultureIgnoreCase))
{
    Console.WriteLine("تم اختيار اللغة العربية");
}
else
{
    Console.WriteLine("Error!");
}

I also added a invariant string check to ignore case (so that "a" and "A" would both be accepted for example) and added a else to the second if statement as general improvements.

Note: Your use of Console.ReadKey() didn't work because it returns a struct that holds information about the input key - this struct will not convert into the original input key if you call Convert.ToString() on it.

If you do really prefer to use Console.ReadKey() then just access the input character using Console.ReadKey().KeyChar.

var input = Convert.ToString(Console.ReadKey().KeyChar);

if (string.Equals(input, "E", StringComparison.InvariantCultureIgnoreCase))
{
    Console.WriteLine("English has been selected");
}
else if (string.Equals(input, "A", StringComparison.InvariantCultureIgnoreCase))
{
    Console.WriteLine("تم اختيار اللغة العربية");
}
else
{
    Console.WriteLine("Error!");
}

Upvotes: 1

Speed Runner
Speed Runner

Reputation: 1

Try this please:

using System;

class Program 
{
    public static void Main (string[] args) 
    {
        string input = Console.ReadLine();

        if (input == "E") 
        {
            Console.WriteLine("English has been selected");
        }
        else if (input == "A")
        {
            Console.WriteLine("تم اختيار اللغة العربية");
        }
        else 
        {
            Console.WriteLine("Error!");
        }
    }
}

Upvotes: -1

Related Questions