5
\$\begingroup\$

I've been learning C# for around 2 weeks and I'm feeling a bit more confident. I wrote this for general practice and am quite proud but hoping to make it faster and more efficient as I progress and learn more.

This program allows the user to input car data i.e. "Model and Price" and then search for the stored data. (Next step is to add more values to the arrays).

class Program
{
    static void Main(string[] args)
    {

        Console.WriteLine("How many cars are in the workshop?");
        int amountofcars = int.Parse(Console.ReadLine());

        int[] cars = new int[amountofcars];
        double[] carprice = new double[amountofcars];
        string[] models = new string[amountofcars];

        for(int i = 0; i < amountofcars; i++)
        {
            Console.WriteLine("List the model of car #{0}", i + 1);
            string carmodels = Console.ReadLine();
            models[i] = carmodels; 
            Console.WriteLine("Input car price");
            double price = double.Parse(Console.ReadLine());
            carprice[i] = price;

        }

            Console.WriteLine("Data stored");

            Console.WriteLine();
            Console.WriteLine("What do you want to do next?");
            Console.WriteLine("Type \"Search\" to start a new search or any key to leave program");
            string responce = Console.ReadLine();
            char searchagain = 'Y';

        do
        {
            if (responce == "Search")
            {
                bool contains = false;
                Console.WriteLine("What car did you want to search for?");
                string modelsearch = Console.ReadLine();

                for (int i = 0; i < amountofcars; i++)
                {
                    if (modelsearch == models[i])
                    {
                        contains = true;
                        Console.WriteLine("{0} {1} ", models[i], carprice[i]);
                        Console.WriteLine();
                        Console.WriteLine("What do you want to do next?");
                        Console.WriteLine("Search again? \"Y\" or any key to exit");
                        searchagain = char.Parse(Console.ReadLine());

                    }
                    if (modelsearch == "All")
                    {
                        for (i = 0; i < amountofcars; i++)
                        {
                            contains = true;
                            Console.WriteLine("{0} {1} ", models[i] , carprice[i]);
                            Console.WriteLine();
                        }
                        Console.WriteLine("What do you want to do next?");
                        Console.WriteLine("Search again? \"Y\" or any key to exit");
                        searchagain = char.Parse(Console.ReadLine());
                    }

                }

            }

        } while (searchagain == 'Y');
    }
}



\$\endgroup\$
0
4
\$\begingroup\$

first, using Parse for user input it would be a bad practice, as you're parsing the input without any validation. thus, you'll need to use TryParse instead, which will validate the input to the specific type, if it's valid input that would be acceptable by the targeted type, then it would return true and output the parsed value.

Example direct parsing :

// this would pass the value without validation 
int amountofcars = int.Parse(Console.ReadLine());

Example of validated parsing :

// this validates the input value, then process :
bool isValid = int.TryParse(Console.ReadLine(), out int amountofcars);
// isValid == true, then it's an interger. 

if(isValid) // if it's a valid integer
{
    // process the amountofcars
}

you'll find a lot of System types that already has TryParse like int.TryParse, double.TryParse and so on. You should always use it when parsing user inputs. You can still use Parse but use it whenever you see that you're diffidently sure a hundred percent that the value will always be compatible with the targeted type.

Since you have cars, carprice and models arrays, I assume you need one class model, that would hold car information. something like :

public class Car
{
    public double Price { get; set; }

    public string Model { get; set; }
}

now you can initiate a car array :

Car[] cars = new Car[amountofcars];

then inside your loop you can simply do this :

for(int i = 0; i < amountofcars; i++)
{
    Console.WriteLine("List the model of car #{0}", i + 1);
    string carmodels = Console.ReadLine();
    cars[i].Model = carmodels; 
    Console.WriteLine("Input car price");
    double price = double.Parse(Console.ReadLine()); // use TryParse instead;
    cars[i].Price = price;
}

doing this, would let you have and process one array which hold the car information in each element.

I suggest you use List instead of array. It would make things easier for you to process like adding and removing and also you don't need to specify its length. Also, it has more functionality than a system array.

Here is a modified version with some comments that would help you throughout the code, if you feel you need a clarification just let me know.

public class Car
{
    public double Price { get; set; }

    public string Model { get; set; }
}

public static class Program
{
    public static void Main(string[] args)
    {
        List<Car> cars = new List<Car>();

        int amountofcars = 0;

        do
        {
            // this should forced the user to input a valid integer 
            // it won't break this loop until it gets a valid integer.
            Console.WriteLine("How many cars are in the workshop?");
        }
        while (int.TryParse(Console.ReadLine(), out amountofcars) == false);

        // now we can process 
        for (int i = 0; i < amountofcars; i++)
        {

            Console.WriteLine("List the model of car #{0}", i + 1);
            // since it's string, there is no need for type validation, unless you need to include business validation. 
            string carmodels = Console.ReadLine();

            // repeat the same validation : 
            double price = 0;
            do
            {
                // this should forced the user to input a valid integer 
                // it won't break this loop until it gets a valid integer.
                Console.WriteLine("Input car price");
            }
            while (double.TryParse(Console.ReadLine(), out price) == false);

            cars.Add(new Car { Model = carmodels, Price = price });
        }


        Console.WriteLine("Data stored");
        Console.WriteLine();
        Console.WriteLine("What do you want to do next?");
        Console.WriteLine("Type \"Search\" to start a new search or any key to leave program");
        string responce = Console.ReadLine();

        while (true)
        {
            //using StringComparison.InvariantCultureIgnoreCase 
            // this would make it case-insensitive
            if (responce.Equals("Search", StringComparison.InvariantCultureIgnoreCase))
            {
                Car found = null;

                Console.WriteLine("What car did you want to search for?");

                string modelsearch = Console.ReadLine();

                foreach (var car in cars)
                {
                    if (car.Model.Equals(modelsearch, StringComparison.InvariantCultureIgnoreCase))
                    {
                        found = car;
                    }
                }

                if (found != null)
                {
                    Console.WriteLine($"{found.Model} {found.Price}");
                    Console.WriteLine();
                }
                else
                {
                    Console.WriteLine($"Model {modelsearch} not found.");
                    Console.WriteLine();
                }

                Console.WriteLine("What do you want to do next?");
                Console.WriteLine("Search again? \"Y\" or any key to exit");


                // this line would break if it's not a char.
                //searchagain = char.Parse(Console.ReadLine());

                var whatnext = Console.ReadLine();

                if (whatnext.Equals("Y", StringComparison.InvariantCultureIgnoreCase) == false)
                {
                    // if user input anything else will break this loop.
                    break;
                }
            }
            else
            {
                // in case if pressed any key, it'll break this loop. 
                break;
            }

        } 

    }
}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Really appreciate your time checking this out. I'm currently doing a course that's yet to get to classes so this will help in the next section of the lecture for sure! Kind of just crammed everything I've currently learned into this program. Thanks a million! \$\endgroup\$
    – cmills95
    Feb 9 '20 at 19:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.