gpt4 book ai didi

c# - 为什么嵌套 if 语句可以工作,但 "&&"运算符却不能? (字母计数脚本)

转载 作者:行者123 更新时间:2023-12-02 01:28:43 24 4
gpt4 key购买 nike

我需要编写一个脚本来计算每个字母在给定文本中出现的次数。我成功地使它工作,虽然我确信有更好的方法来做到这一点,但脚本做了它应该做的事情:

    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();
}

使用此代码,Y当且仅当 A 时执行是 false ,无论 B 的值如何.

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

使用此代码,Y如果 A 则执行是 true但是Bfalse 。添加else block 意味着每种情况下的逻辑都不相同。删除else在这两种情况下, block 和剩下的内容在功能上是等效的。

关于c# - 为什么嵌套 if 语句可以工作,但 "&&"运算符却不能? (字母计数脚本),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73797639/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com