我创建了一个 foreach 循环,以便它遍历数组的每个项目。我试图将东西放入我的 if 语句中,但我尝试的任何内容似乎都无法编译我尝试放入歌曲的 getartist 但这不起作用,因为它是一种方法。
我需要检查艺术家是否与用户输入的艺术家匹配,或者如果用户在没有输入艺术家的情况下按下返回,那么它应该显示歌曲的详细信息。
我假设第二部分使用 keyread 函数,但我不完全确定如何使用它。
class Program
{
static void Main(string[] args)
{
Song[] songs = new Song[4];
for (int i = 0; i < songs.Length; i++)
{
songs[i] = InputSongDetails();
}
Console.WriteLine("Enter an artist name, or just press return for all artists");
foreach (var song in songs)
{
if ()
{
}
}
}
static Song InputSongDetails()
{
Console.WriteLine("What is the name of your song");
string name = Console.ReadLine();
Console.WriteLine("What is the artists name");
string artist = Console.ReadLine();
int records;
Console.WriteLine("How many records did it sell");
while (!int.TryParse(Console.ReadLine(), out records) || records < 0)
{
Console.WriteLine("That is not valid please enter a number");
}
return new Song(name, artist, records);
}
}
歌曲班
class Song
{
string name;
string artist;
int copiesSold;
public Song(string name, string artist, int copiesSold)
{
this.name = name;
this.artist = artist;
this.copiesSold = copiesSold;
}
public Song()
{
}
public string GetArtist()
{
return artist;
}
public string GetDetails()
{
return $"Name: {name} Artist: {artist} Copies Sold: {copiesSold},";
}
public string GetCertification()
{
if (copiesSold < 200000)
{
return null;
}
if (copiesSold < 400000)
{
return "Silver";
}
if (copiesSold < 600000)
{
return "Gold";
}
return "Platinum";
}
}
你错过了几件事。
首先,您需要从用户那里读取艺术家姓名。
Console.WriteLine("Enter an artist name, or just press return for all artists");
var artist = Console.ReadLine();
然后您需要根据用户输入过滤歌曲列表,
foreach (var song in songs)
{
if (string.IsNullOrWhiteSpace(artist) || song.GetArtist().Equals(artist))
{
Console.WriteLine(song.GetDetails());
}
}
顺便说一句,为了展示另一种方法,您也可以在这里使用 Linq。
var filteredList= songs.Where(song=>string.IsNullOrWhiteSpace(artist) || song.GetArtist().Equals(artist))
.Select(song=> song.GetDetails());
Console.WriteLine(string.Join(Environment.NewLine, filteredList));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句