简体   繁体   中英

Beginner to Array c#

I don't really understand arrays and I need to create a variable of type 'array of songs' then initialize it to a new Array so it can store 4 references to Songs. How would I then create a loop that would run enough times to fill the array whilst calling the InputSOngDetails() method and store the return value in that method?

namespace Songs
{
    class Program
    {
        static void Main(string[] args) {
            InputSongDetails();
        }

        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);
        }
    }
}

This is my Songs class if needed

namespace Songs
{
    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";  
        }
    }
}

Fist, initialize your array of songs with new Song[ length ] , then a simple for -loop will suffice.

static void Main(string[] args) 
{
    Song[] songs = new Song[4];
    for(int i = 0; i < songs.Length; i++) 
    {
        songs[i] = InputSongDetails();
    }
}

Or as the commenters suggest, just use a variable-length List<Song> .

static void Main(string[] args) 
{
    List<Song> songs = new List<Song>();
    for(int i = 0; i < 4; i++) 
    {
        songs.Add(InputSongDetails());
    }
}

Once you've mastered the basics, you can also accomplish this with a bit of Linq (though I wouldn't actually recommend it in this case):

static void Main(string[] args) 
{
    var songs = Enumerable.Range(0, 4)
                          .Select(i => InputSongDetails())
                          .ToList();
}

This is not really an answer as much as it is a tip for getting input from the user in a console application which might be useful to you (well, the answer is in the last code snippet, but pswg has already covered that very well).

Since an interactive console session usually ends up with a lot of Console.WriteLine("Ask the user a question"); string input = Console.ReadLine(); Console.WriteLine("Ask the user a question"); string input = Console.ReadLine(); , and, as you've already done very well, include some validation on the input in some cases, I've found it handy to write the following methods below.

Each of them take in a string , which is the prompt for the user (the question), and return a strongly-typed variable that represents their input. Validation (when needed) is all done in a loop in the method (as you've done):

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;
}

With these methods in place, getting input is as simple as:

string name = GetStringFromUser("Enter your name: ");
int age = GetIntFromUser("Enter your age: ");

And it makes writing the method to get a Song from the user that much easier:

private static Song GetSongFromUser()
{
    return new Song(
        GetStringFromUser("Enter song name: "),
        GetStringFromUser("Enter Artist name: "),
        GetIntFromUser("Enter number of copies sold: "));
}

So now our main method just looks like (and this is the answer to your question):

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...");
}

Additionally, here are some suggestions for improving the Song class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM