【发布时间】:2022-01-02 21:05:52
【问题描述】:
这是控制台程序中的 C# 类
public class Person
{
public string Name;
public int BirthYear;
public int Age(int birthYear)
{
DateTime presents = DateTime.Now;
int presentAge = presents.Year - birthYear;
return presentAge;
}
}
也是主程序
static void Main(string[] args)
{
Console.WriteLine("Input peoples: ");
int people = Convert.ToInt32(Console.ReadLine());
Person a = new Person();
for(int i = 0; i < people; i++)
{
Console.WriteLine("Person {0}", i + 1);
Console.Write("Enter the name: ");
a.Name = Console.ReadLine();
Console.Write("Enter the birth year: ");
a.BirthYear = Convert.ToInt32(Console.ReadLine());
int present = a.Age(a.BirthYear);
Console.WriteLine("Hello {0}, your age is {1} years old", a.Name, present);
}
}
我输入了2个人,结果是这样的:
Person 1
Enter the name: Lu Bu
Enter the birth year: 1998
Hello Lu Bu, your age is 23 years old
Person 2
Enter the name: Diao Chan
Enter the birth year: 2000
Hello Diao Chan, your age is 21 years old
我想达到这样的结果:
Person 1
Enter the name: Lu Bu
Enter the birth year: 1998
Person 2
Enter the name: Diao Chan
Enter the birth year: 2000
Hello Lu Bu, your age is 23 years old
Hello Diao Chan, your age is 21 years old
是否可以仅使用for 循环来实现,还是必须使用List<>?
PS:我的意思是问题中的列表不是 List<>虽然
【问题讨论】:
-
所以您想要一个循环来获取所有用户输入,然后完成后,您想打印您提交的所有数据吗?那么您将需要一种方法来从这两个循环中传输数据。
-
您可以在循环内将 Hello 消息附加到 StringBuilder 并在循环退出后将其写入 Console。是这个意思吗?
-
如果没有两个循环和某种集合,我看不出你会怎么做。
-
您的人数不确定,因此您需要一个集合来存储他们,然后是一个循环来为每个人写下您的句子。无论如何,在您的示例中,每个人都会覆盖前一个,因为只有一个 Person 实例。我怀疑这是你想要的吗?
-
@PostJavanese 有人打败了我,虽然我不会同时使用 .AppendLine() 和 .Append(),但我只会使用 .AppendLine("...消息... ")