2017-04-23 25 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變量重命名爲一個更具可讀性的名字。

相關問題