Здравствуйте, я хотел бы знать, как я могу принять пользовательский ввод из одного метода и использовать эти новые сохраненные данные, чтобы распечатать их в другом методе? - PullRequest
0 голосов
/ 27 марта 2020
  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);
        }
    }


    ***

Вывод, который я пытаюсь получить: Введите название города вашей любимой спортивной команды: Нью-Йорк. Теперь введите название их команды: Янки Введите дату, когда вы стали поклонником этой спортивной команды: 3 / 26/2020 Нью-Йорк Янкиз стал моей любимой командой 3/26/2020


Ответы [ 2 ]

1 голос
/ 27 марта 2020

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. Вот почему я изменил метод, чтобы он возвращал строку, и тогда мы можем сохранить то, что метод возвращает в переменной.

0 голосов
/ 27 марта 2020

Просто переместите набор определения cityName, teamName и fanDate в верхнюю часть вашего Main () {здесь}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...