2016-10-12 13 views
2
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace Methods 
{ 
    class Program 
    { 
     static string firstName; 
     static string lastName; 
     static string birthday; 

     static void Main(string[] args) 
     { 
      GetStudentInformation(); 
      //PrintStudentDetails(firstName, lastName,birthDay); 
      Console.WriteLine("{0} {1} {2}", firstName, lastName, birthday); 
      Console.ReadKey(); 
     } 

     static void GetStudentInformation() 
     { 
      Console.WriteLine("Enter the student's first name: "); 
      string firstName = Console.ReadLine(); 
      Console.WriteLine("Enter the student's last name"); 
      string lastName = Console.ReadLine(); 
      Console.WriteLine("Enter the student's birthday"); 
      string birthday = Console.ReadLine(); 

      //Console.WriteLine("{0} {1} {2}", firstName, lastName, birthDay); 

     } 

     static void PrintStudentDetails(string first, string last, string birthday) 
     { 
      Console.WriteLine("{0} {1} was born on: {2}", first, last, birthday); 
     } 
    } 
} 

私はクラス変数を宣言する方法について私に様々な方法をお勧めしましたが、私が提示するすべての解決策はうまくいかないようです。私は3つの変数にユーザーからの入力を保存しようとしています。姓、名、誕生日。プログラムを実行するたびに値を要求し、変数を出力しようとすると空行のみが表示されます。クラス変数を使ったメソッド呼び出しの取得方法を教えてください。

どのようにしてこのように変数を出力できますか?このセクションでは

+0

印刷で使用される3つのグローバル変数を再宣言しています。これはグローバル変数を隠し、コードがGetStudentInformationを終了した直後に破棄される3つのローカル変数で発生します。 – Steve

答えて

2

Console.WriteLine("Enter the student's first name: "); 
string firstName = Console.ReadLine(); 

Console.WriteLine("Enter the student's last name"); 
string lastName = Console.ReadLine(); 

Console.WriteLine("Enter the student's birthday"); 
string birthday = Console.ReadLine(); 

あなただけの方法の適用範囲のためにそれらの名前を持つ新しい変数を作成していると、クラスのものに割り当てるされていません。彼らの前にstringを削除します。

Console.WriteLine("Enter the student's first name: "); 
firstName = Console.ReadLine(); 

Console.WriteLine("Enter the student's last name"); 
lastName = Console.ReadLine(); 

Console.WriteLine("Enter the student's birthday"); 
birthday = Console.ReadLine(); 

私はVariable and Method Scopeにもっと読んで示唆しています。 はまた、私はあなたが静的クラスの使用に多くを見て、読むべきだと思う:When to use static classes in C#

スティーブは彼の答えで示唆したように、あなたがクラスStudentを作成し、それを移入することをお勧めします。しかし、このコードに適合していますが、私はstaticを宣言しませんでしたが、ユーザーの入力を要求する関数から戻しました。

+0

@zstaylor - これは問題の解決に役立ちましたか? –

関連する問題