简体   繁体   English

为什么嵌套的 if 语句可以工作,而“&&”运算符却不行? (字母计数脚本)

[英]Why does a nested if-statement work, but the "&&" operator doesn't? (letter counting script)

I need to write a script that counts how many times each letter occurs in a given text.我需要编写一个脚本来计算每个字母在给定文本中出现的次数。 I was successful at making it work, and although I'm sure that there's a better way to do it, the script does what it's supposed to do:我成功地让它工作了,虽然我确信有更好的方法来做到这一点,但脚本做了它应该做的事情:

    static void Main(string[] args)
    {
        string text;
        Dictionary<char, int> letterCount = new Dictionary<char, int>();
        List<char> nonLetters = new List<char>
        {
            '.', '!', ',', '?', ':', ';', '#', '@', '$', '&', '(',')', '-',
            '+', '=', '\"','\'', ' ', '\n', '1', '2', '3', '4', '5', '6',
            '7', '8','9', '0'
        };
        Console.WriteLine("Enter your text");
        text = Console.ReadLine();
        text = text.ToLower();
        for(int i = 0; i < text.Length; i++)
        {
            if (!letterCount.ContainsKey(text[i]))
            {
                if (!nonLetters.Contains(text[i]))
                {
                    letterCount.Add(text[i], 1);
                }
            }
            else
            {
                letterCount[text[i]] += 1;
            }
        }


        foreach (KeyValuePair<char, int> kvp in letterCount)
        {
            Console.WriteLine($"{kvp.Key}: {kvp.Value}");
        }
        Console.ReadKey();
    }

My first attempt wasn't successful, though.不过,我的第一次尝试并不成功。 And I don't understand why and what the difference is.而且我不明白为什么以及有什么区别。 This is what the for-loop in my initial code looked like:这就是我最初代码中的 for 循环的样子:

for(int i = 0; i < text.Length; i++)
        {
            if (!letterCount.ContainsKey(text[i]) && !nonLetters.Contains(text[i]))
            {
                letterCount.Add(text[i], 1);
            }
            else
            {
                letterCount[text[i]] += 1;
            }
        }

This is what the Exception message says: System.Collections.Generic.KeyNotFoundException "The given key'(' was not present in the dictionary这就是异常消息所说的内容: System.Collections.Generic.KeyNotFoundException "The given key'(' was not present in the dictionary

Please, help me understand why using the "&&" operator doesn't work while the embedded if-statement with the same condition does.请帮助我理解为什么使用“&&”运算符不起作用,而具有相同条件的嵌入式 if 语句起作用。

if (A)
{
    if (B)
    {
        X();
    }
}
else
{
    Y();
}

With this code, Y is executed if and only if A is false , regardless of the value of B .使用此代码,当且仅当Afalse时,才执行Y ,而不管B的值。

if (A && B)
{
    X();
}
else
{
    Y();
}

With this code, Y is executed if A is true but B is false .使用此代码,如果AtrueBfalse ,则执行Y The addition of the else blocks means that the logic is not the same in each case. else块的添加意味着每种情况下的逻辑都不相同。 Remove the else blocks and what's left will be functionally equivalent in both cases.删除else块,剩下的将在这两种情况下功能相同。

The problem with your original code is not to do with the syntax but the logic;原始代码的问题与语法无关,而与逻辑有关; it does not handle the case where the character being read is a non-letter well.它不处理正在读取的字符是非字母的情况。

In the scenario that the character being read is a non-letter, the if statement will be false.在读取的字符是非字母的情况下,if 语句为 false。 In this instance the code will attempt to increment the count for that non-letter character but it will not exist in the dictionary because the code does not add non-letter to the dictionary.在这种情况下,代码将尝试增加该非字母字符的计数,但它不会存在于字典中,因为代码不会将非字母添加到字典中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM