[英]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.