c# - 您好,我想知道如何接受来自一种方法的用户输入并使用新存储的数据在另一种方法中打印出来?
问题描述
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 日最喜欢的球队
解决方案
根据你的结构,你可以做这样的事情。了解变量范围很重要(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 方法之外。这就是为什么我将方法更改为返回字符串,然后我们可以将方法返回的内容存储在变量中。
推荐阅读
- testing - “软件测试”的实际含义是什么?
- flutter - Flutter 合并多个流 Flutter 以在 Firestore 中执行 OR 查询
- python - Python将多个键/唯一对匹配到一个值
- python - TensorFlow CNN 不兼容的形状:4D 输入形状
- node.js - 销毁 NodeJs 流导致客户端断开连接
- javascript - 两种方法在一种方法中实现 - 角度
- java - 在 Random.java 中,不是 x&((1L<<48)-1)==x 吗?
- c++ - 为什么这个 c++ 代码会产生奇怪的字符?
- angular - Select box in does not bind to component.ts
- javascript - 在反应中将纯字符串转换为html