I'm writing an application in C# that prompts the user for data for objects of an Automobile class. One of the properties of the class for which the program prompts the user for data is ID number. If any ID number during data entry is a duplicate, the program must reprompt the user. How can I do that?
Here is the code for the class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomobileDemo
{
internal class Automobile : IComparable
{
public int ID { get; set; }
public string Make { get; set; }
public int Year { get; set; }
public double Price { get; set; }
public override string ToString()
{
return ID + ": " + Make + " - " + Year + " - " + Price.ToString("C");
}
int IComparable.CompareTo(object obj)
{
Automobile anAutomible = (Automobile)obj;
return this.ID.CompareTo(anAutomible.ID);
}
}
}
Here is the code for the main class:
namespace AutomobileDemo
{
internal class Program
{
static void Main(string[] args)
{
Automobile[] cars = new Automobile[8];
double totalPrices = 0;
for (int i = 0; i < cars.Length; ++i)
{
cars[i] = new Automobile();
Console.Write("ID number: ");
cars[i].ID = Convert.ToInt32(Console.ReadLine());
Console.Write("Make: ");
cars[i].Make = Console.ReadLine() ?? "";
Console.Write("Year: ");
cars[i].Year = Convert.ToInt32(Console.ReadLine());
Console.Write("Price: ");
cars[i].Price = Convert.ToDouble(Console.ReadLine());
totalPrices += cars[i].Price;
Console.WriteLine();
}
Array.Sort(cars);
for (int i = 0; i < cars.Length; ++i)
Console.WriteLine(cars[i].ToString());
Console.WriteLine("\nTotal of all prices: " + totalPrices.ToString("C"));
}
}
}