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(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
Please, help me understand why using the "&&" operator doesn't work while the embedded if-statement with the same condition does.
CodePudding user response:
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
.
if (A && B)
{
X();
}
else
{
Y();
}
With this code, Y
is executed if A
is true
but B
is false
. The addition of the else
blocks means that the logic is not the same in each case. Remove the else
blocks and what's left will be functionally equivalent in both cases.
CodePudding user response:
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. 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.