Making a Hangman game. I want in this function to take the 'Answer' which has been validated elsewhere in my code and split it into its individual letters and then Hangman equivalent representative.
e.g.:
abc == ___
hi world == __/_____ and so on..
I am using a 2d array 'UncoveredArray' to hold this data. I want to now return it to my main so that it can be used for the next step of the game in another method.
static void Main(string[] args)
{
NewGame Hangman = new NewGame();
string Answer = Hangman.GetWord();
var UncoveredArray = new char[Answer.Length, 2];
UncoveredArray = Hangman.ProcessWord(Answer, out UncoveredArray);
public char[] ProcessWord(string Answer, out char UncoveredArray)
{
char[] chars = Answer.ToCharArray();
var UncoveredArray = new char[chars.Length, 2];
for (int i = 0; i < Answer.Length; i )
{
if (chars[i] == ' ')
{
Console.Write("/");
UncoveredArray[i, 0] = chars[i];
UncoveredArray[i, 1] = '/';
}
else if (char.IsPunctuation(chars[i]))
{
Console.Write(chars[i]);
UncoveredArray[i, 0] = chars[i];
UncoveredArray[i, 1] = chars[i];
}
else
{
Console.Write("_");
UncoveredArray[i, 0] = chars[i];
UncoveredArray[i, 1] = '_';
}
}
return UncoveredArray;
//TODO: RETURN ARRAY
}
CodePudding user response:
The confusion arises from unnecessary use of a out
parameter. Simplify things: just return a new instance
public char[,] ProcessWord(string answer) {} //logic remains more or less the same
//in Main() use it like
char [,] uncoveredArray = hangman.ProcessWord(answer);
Notice in your original method, you pass in the char[,] UncoveredArray
as an output parameter and then immediately cobbler it with var UncoveredArray = new char[chars.Length, 2];
. This is not only pointless but this won't even compile. Be careful, you never want to attempt to create a new variable with the same name, especially when its the name of a parameter. As far as I know C# doesn't support something like Rust's "shadowing" which allows such a phenomenon
Also the return type must be char[,]
not char[]
. The first is an actual 2D array, while the first is 1D
Use of explicit typing, rather than var
helps out a lot in cases like this. Please be sure to follow proper naming conventions for variables, classes, and methods as well