2 回答

TA貢獻1111條經驗 獲得超0個贊
拳頭,初始化你的歌曲數組,然后一個簡單的for循環就足夠了。new Song[ length ]
static void Main(string[] args)
{
Song[] songs = new Song[4];
for(int i = 0; i < songs.Length; i++)
{
songs[i] = InputSongDetails();
}
}
或者正如評論者所建議的那樣,只需使用可變長度的List<Song>。
static void Main(string[] args)
{
List<Song> songs = new List<Song>();
for(int i = 0; i < 4; i++)
{
songs.Add(InputSongDetails());
}
}
一旦你掌握了基礎知識,你也可以用一點Linq來完成這個(盡管在這種情況下我實際上并不建議這樣做):
static void Main(string[] args)
{
var songs = Enumerable.Range(0, 4)
.Select(i => InputSongDetails())
.ToList();
}

TA貢獻1772條經驗 獲得超6個贊
這并不是一個真正的答案,而是一個在控制臺應用程序中從用戶獲取輸入的提示,這可能對你有用(好吧,答案在最后一個代碼片段中,但p.s.w.g已經很好地涵蓋了這一點)。
由于交互式控制臺會話通常以很多 結束,并且,正如您已經做得很好的那樣,在某些情況下對輸入進行一些驗證,我發現在下面編寫以下方法很方便。Console.WriteLine("Ask the user a question"); string input = Console.ReadLine();
它們中的每一個都采用 一個 ,這是用戶的提示(問題),并返回一個表示其輸入的強類型變量。驗證(在需要時)全部在方法的循環中完成(如您所做的那樣):string
private static ConsoleKeyInfo GetKeyFromUser(string prompt)
{
Console.Write(prompt);
var key = Console.ReadKey();
Console.WriteLine();
return key;
}
private static string GetStringFromUser(string prompt)
{
Console.Write(prompt);
return Console.ReadLine();
}
public static int GetIntFromUser(string prompt = null)
{
int input;
int row = Console.CursorTop;
int promptLength = prompt?.Length ?? 0;
do
{
Console.SetCursorPosition(0, row);
Console.Write(prompt + new string(' ', Console.WindowWidth - promptLength - 1));
Console.CursorLeft = promptLength;
} while (!int.TryParse(Console.ReadLine(), out input));
return input;
}
有了這些方法,獲取輸入就像:
string name = GetStringFromUser("Enter your name: ");
int age = GetIntFromUser("Enter your age: ");
它使編寫方法以從用戶那里獲取方法變得更加容易:Song
private static Song GetSongFromUser()
{
return new Song(
GetStringFromUser("Enter song name: "),
GetStringFromUser("Enter Artist name: "),
GetIntFromUser("Enter number of copies sold: "));
}
所以現在我們的主要方法看起來像這樣(這是你問題的答案):
private static void Main()
{
var songs = new Song[4];
for (int i = 0; i < songs.Length; i++)
{
songs[i] = GetSongFromUser();
}
Console.WriteLine("\nYou've entered the following songs: ");
foreach (Song song in songs)
{
Console.WriteLine(song.GetDetails());
}
GetKeyFromUser("\nDone! Press any key to exit...");
}
此外,下面是一些改進類的建議。Song
- 2 回答
- 0 關注
- 114 瀏覽
添加回答
舉報