Home > Software engineering >  How to let a user add new objects in a list?
How to let a user add new objects in a list?

Time:10-04

In my Console App the user can currently add a new object by pressing the " " key, but how can I let him later on change a specific object in the list? For example.

The list is of boats. I want each boat to continously get a specific name, i.e boat1, boat2, boat3, etc. And if a user adds another boat it will get then name boat4, and so on, so that he later in the application can change the speed of a specific boat by calling its name.

Boats boat1 = new Boats();
boat1.Speed = 15;
Boats boat2 = new Boats();
boat2.Speed = 26;

List<Boats> boatList = new List<Boats>();

boatList.Add(boat1);
boatList.Add(boat2);

And in the Boats.cs I have this method:

public static void NewBoat()
{
    var newBoat = new Boats();

    Console.WriteLine("\nIf you want to create a new boat, press  ");
    if (Console.ReadKey().KeyChar == ' ') 
    {
        var newBoats = new Boats();
        newBoat.AddBoatList(newBoats);
    }
    else 
    {
        Console.WriteLine("\nInvalid Input.");
    }

CodePudding user response:

boat1 and boat2 are just variable names, not the name of the object. If you add them to the list the list doesn't know anything about the names. If you want to have the name in the list you should have a String with the name as part of the Boats class to which you assign the name. Later you can search for the name in the list. To generate the variables it's better to do it in the way of your second part in Boats.cs: not for each boat an extra variable, just one variable which process the new before you assign the data to it and add it to the list.

CodePudding user response:

You need to save the names of the boats in the list and then you can create a function to retrieve the boat name and then you can change it

  • Related