2016-10-12 26 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

您将重新声明打印中使用的三个全局变量。这隐藏了全局变量和输入发生在代码从GetStudentInformation退出后立即丢弃的三个局部变量 – 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 - 这是否帮助您解决问题? –

相关问题