2017-04-23 30 views
-1

//我必须创建一个程序,确定名称是否以正确的格式写入,然后一旦它认为正确,它会将名字和姓氏。C#。我不断收到一个错误,指出我有“使用未分配的本地变量'全名'”

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(); 
    } 
} 
+1

给全名分配一个初始值即:'bool fullname = false;' – Nkosi

回答

0

声明没有初始值的变量,然后用if语句没有确定的值没有任何意义返回它的方法。如果您想return的值,您必须为fullname指定一个值。

初始化这个变量第一:

bool fullname = false; 
1

永远记住为C#这3个规则:

  1. 要使用一个变量,它必须被初始化。
  2. 现场成员初始化为默认值
  3. 当地人不会初始化为默认值。

您正在违反规则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变量重命名为一个更具可读性的名字。

相关问题