這是控制臺程式中 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<>雖然
uj5u.com熱心網友回復:
您可以存盤提供的資訊 ( hellos) 并在最后列印。您不必使用List<string>,它可以是任何集合(例如,Queue<string>)甚至是StringBuilder:
StringBuilder hellos = new StringBuilder();
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);
// Instead of printing, we collect the data...
if (hellos.Length > 0)
hellos.AppendLine();
hellos.Append($"Hello {a.Name}, your age is {present} years old");
}
// ...and after the loop we print out all the data collected
Console.WriteLine(hellos);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/365907.html
上一篇:遞回數字和
下一篇:如何在陣列中找到三個最大的數字?
