So in my class we are doing a pig latin translator using Winforms. If I copy the formula from my Convert function to the click event it works perfectly fine for 1 word. However I can not get this to function correctly otherwise.
This is the code I currently have, the problem it is giving me is that the output label is not giving me the converted word. Instead it is giving me this message:
For example say I input 'Bob' I get this as my output: "System.Collections.Generic.List`1[System.String]Bob"
private void btn_Translate_Click(object sender, EventArgs e)
{
string userInput = box_Input.Text;
if (userInput.Contains(" "))
{
string[] words = userInput.Split(' ');
foreach (var word in words)
{
Validator(word);
}
}
else
{
Validator(userInput);
}
}
public void Validator(string s)
{
string chkInput = s;
if (string.IsNullOrEmpty(chkInput))
{
Error(1);
Error(0);
}
else
{
if (chkInput.Length < 2)
{
Error(1);
Error(0);
}
else
{
if (!chkInput.Any(x => char.IsLetter(x)))
{
Convert(chkInput);
}
else
{
Error(3);
Error(0);
}
}
}
}
public void Convert(string convInput)
{
string word = convInput;
string charStrNew;
string firstLetter = word.Substring(0, 1);
string theRest = word.Substring(1, word.Length - 1);
string suffix = "ay";
charStrNew = $"{theRest}{firstLetter}{suffix}";
string listStrOutput = String.Join(" ", charStrNew);
lbl_Output.Text = listStrOutput;
}
CodePudding user response:
You have an error in your Validator
. Replace the !chkInput.Any(x => char.IsLetter(x))
with !chkInput.Any(x => !char.IsLetter(x))
or even better, use Enumerable.All
: chkInput.All(char.IsLetter)
Determines whether all elements of a sequence satisfy a condition.
public static void Main()
{
btn_Translate_Click("bob");
}
public static void btn_Translate_Click(string userInput)
{
if (userInput.Contains(" "))
{
string[] words = userInput.Split(' ');
foreach (var word in words)
{
Validator(word);
}
}
else
{
Validator(userInput);
}
}
public static void Error(int output)
{
Console.WriteLine(output);
}
public static void Validator(string s)
{
string chkInput = s;
if (string.IsNullOrEmpty(chkInput))
{
Error(1);
Error(0);
}
else
{
if (chkInput.Length < 2)
{
Error(1);
Error(0);
}
else
{
if (chkInput.All(char.IsLetter))
{
Console.WriteLine(Convert(chkInput));
}
else
{
Error(3);
Error(0);
}
}
}
}
public static string Convert(string convInput)
{
string word = convInput;
string charStrNew;
string firstLetter = word.Substring(0, 1);
string theRest = word.Substring(1, word.Length - 1);
string suffix = "ay";
charStrNew = $"{theRest}{firstLetter}{suffix}";
string listStrOutput = String.Join(" ", charStrNew);
return listStrOutput;
}