所以在我的課堂上,我們正在使用 Winforms 做一個豬拉丁語翻譯器。如果我將公式從我的 Convert 函式復制到 click 事件,它對于 1 個字來說效果很好。但是,否則我無法使其正常運行。
這是我目前擁有的代碼,它給我的問題是輸出標簽沒有給我轉換后的單詞。相反,它給了我這樣的資訊:
例如說我輸入'Bob'我得到這個作為我的輸出:“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;
}
uj5u.com熱心網友回復:
您的Validator. 更換!chkInput.Any(x => char.IsLetter(x))用!chkInput.Any(x => !char.IsLetter(x))或者甚至更好,使用Enumerable.All:chkInput.All(char.IsLetter)
確定序列的所有元素是否都滿足條件。
msdn
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;
}
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/355143.html
