首页 > 解决方案 > 您好,我想知道如何接受来自一种方法的用户输入并使用新存储的数据在另一种方法中打印出来?

问题描述

  class Program
  {
     static void Main(string[] args)
     {
        Program.GetSportsTeam(); //Call the void method to get SportsTeam information

         string city = GetSportsTeam(cityName); //Get the stored user input from the function
         string team = GetSportsTeam(teamName);//and store that information in new variables
         string date = GetSportsTeam(fanDate);//in order to print using the called print menthod

            Program.PrintSportsTeam(city, team, date);
      }

        static void GetSportsTeam()
        {
            //Get users Sports team info
            Console.WriteLine("Enter the city of your favorite sports team:");
            string cityName = Console.ReadLine();

            Console.WriteLine("Now enter their team name:");
            string teamName = Console.ReadLine();

            Console.WriteLine("Enter the date roughly of when you became a fan of said sports team:");
            DateTime fanDate = System.DateTime.Parse(Console.ReadLine());
        }

            static void PrintSportsTeam(string city, string team, string date)
        {

            Console.WriteLine("{0}{1} became my favorite team on: {2}", city, team, date);
        }
    }


    ***

我想要得到的输出是:输入您最喜欢的运动队的城市名称:纽约现在输入他们的队名:洋基队输入您成为该运动队球迷的日期:2020 年 3 月 26 日纽约洋基队成为我的2020 年 3 月 26 日最喜欢的球队


标签: c#

解决方案


https://pastebin.com/WuKNnNsi

根据你的结构,你可以做这样的事情。了解变量范围很重要(https://www.pluralsight.com/guides/know-scope-local-variables)。所以当你有类似的东西时:

 static void GetSportsTeam()
        {
            //Get users Sports team info
            Console.WriteLine("Enter the city of your favorite sports team:");
            string cityName = Console.ReadLine();

            Console.WriteLine("Now enter their team name:");
            string teamName = Console.ReadLine();

            Console.WriteLine("Enter the date roughly of when you became a fan of said sports team:");
            DateTime fanDate = System.DateTime.Parse(Console.ReadLine());
        }

您的变量 cityName、teamname 和 fanDate 不会存在于 GetSportsTeam 方法之外。这就是为什么我将方法更改为返回字符串,然后我们可以将方法返回的内容存储在变量中。


推荐阅读