[英]Why does a nested if-statement work, but the "&&" operator doesn't? (letter counting script)
我需要编写一个脚本来计算每个字母在给定文本中出现的次数。 我成功地让它工作了,虽然我确信有更好的方法来做到这一点,但脚本做了它应该做的事情:
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();
}
不过,我的第一次尝试并不成功。 而且我不明白为什么以及有什么区别。 这就是我最初代码中的 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;
}
}
这就是异常消息所说的内容: System.Collections.Generic.KeyNotFoundException "The given key'(' was not present in the dictionary
请帮助我理解为什么使用“&&”运算符不起作用,而具有相同条件的嵌入式 if 语句起作用。
if (A)
{
if (B)
{
X();
}
}
else
{
Y();
}
使用此代码,当且仅当A
为false
时,才执行Y
,而不管B
的值。
if (A && B)
{
X();
}
else
{
Y();
}
使用此代码,如果A
为true
但B
为false
,则执行Y
。 else
块的添加意味着每种情况下的逻辑都不相同。 删除else
块,剩下的将在这两种情况下功能相同。
原始代码的问题与语法无关,而与逻辑有关; 它不处理正在读取的字符是非字母的情况。
在读取的字符是非字母的情况下,if 语句为 false。 在这种情况下,代码将尝试增加该非字母字符的计数,但它不会存在于字典中,因为代码不会将非字母添加到字典中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.