I am trying to check whether the key that the user presses is equal to the key in a word. e.g. the word is "flower" and the user enters "f" the output should be true, if the user presses "x" the output should be false. When I try to enter a character it give me System.InvalidCastException: 'Unable to cast object of type 'System.Char[]' to type 'System.IConvertible'.' where the code checks if user input matches key in the word.
private bool KeyCheck(char key)
{
//word arraylist values set to word in array currentWords at index 0
word.Add((currentWords[0].ToCharArray()));
for (int i = 0; i < word.Count; i )
{
//checks if user input matches key in word
if (Convert.ToChar(word[i]) == key)
{
correct ;
return true;
}
}
incorrect ;
return false;
}
CodePudding user response:
private bool KeyCheck(char key)
{
return currentWords[0].Contains(key);
}
CodePudding user response:
If you want just to check if key is within currentWords[0], try Contains:
// Assuming that currentWords[0] is never null
private bool KeyCheck(char key) => currentWords[0].Contains(key);
However, as I can see, you have some correct and incorrect counters; if they must be kept as well as words we can use Contains again but with some extra logic:
private bool KeyCheck(char key) {
word.Add((currentWords[0].ToCharArray()));
// Let it be a good old loop; I have put "char[] w", not "var w"
// to be evident what's going on
foreach (char[] w in words) {
if (w.Contains(key)) {
correct ;
return true;
}
}
incorrect ;
return false;
}
Linq solution (we query words) can be something like this:
using System.Linq;
...
private bool KeyCheck(char key) {
word.Add((currentWords[0].ToCharArray()));
bool result = words.Any(w => w.Contains(key));
if (result)
correct ;
else
incorrect ;
return result;
}
CodePudding user response:
word[i] is of type System.Char[] like the exception says which can't be converted to a character. Not sure what type currentWords is but if it's a string array then when you add currentWords[0] to word you can do
word.Add(Convert.ToChar(currentWords[0]));
and then your if statement would just be
if (word[i] == key)
