//我必须创建一个程序来确定名称是否以正确的格式写入,然后一旦认为它正确就分开了名字和姓氏。
public partial class nameFormatForm : Form
{
public nameFormatForm()
{
InitializeComponent();
}
private bool IsValidFullName(string str)
{
bool letters;
bool character;
bool fullname;
foreach (char ch in str)
{
if (char.IsLetter(ch) && str.Contains(", "))
{
fullname = true;
}
else
{
MessageBox.Show("Full name is not in the proper format");
}
}
return fullname;
}
private void exitButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void clearScreenButton_Click(object sender, EventArgs e)
{
exitButton.Focus();
displayFirstLabel.Text = "";
displayLastLabel.Text = "";
nameTextBox.Text = "";
}
private void formatNameButton_Click(object sender, EventArgs e)
{
clearScreenButton.Focus();
}
}
答案 0 :(得分:1)
永远记住C#的这三条规则:
您违反规则1:在初始化之前使用fullname
。以下程序将澄清这一点:
public class Program
{
public static void Main()
{
// This is a local and NOT initialized
int number;
var person = new Person();
Console.WriteLine(person.age); // This will work
Console.WriteLine(number); // This will not work
Console.Read();
}
}
public class Person
{
// This is a field so it will be initialized to the default of int which is zero
public int age;
}
要解决您的问题,您需要初始化fullname
:
bool fullname = false;
我会将变量重命名为更易读的名称,例如isFullName
。
答案 1 :(得分:0)
声明一个没有初始值的变量,然后在一个没有确定值的if
语句的方法中返回它没有任何意义。如果您想要fullname
其值,则必须为return
分配值。
首先创建此变量:
bool fullname = false;