I am learning C# on my own and am stuck on an exercise. I need to ensure that no duplicate OrderNumbers are entered into my order array. I think the idea of the exercise was to use Equals() however, I could not figure out how to get it to work. I haven't learned anything too fancy yet. Would Equals() be better than using a method for this? Also, I am not sure how to call the method so I see the true or false values. If a duplicate is found, it should loop and ask user to re-enter. Thanking you in advance as I am really frustrated... I so need a mentor!
class Program
{
static void Main()
{
Order[] order = new Order[3];
int orderNumber; // hold temp value until object is created
string customerName;
int qtyOrdered;
for (int x = 0; x < order.Length; ++x) //to fill array
{
Console.Write("Enter Order Number: ");
int.TryParse(Console.ReadLine(), out orderNumber); // put order number in temp
if (order[x] != null)
{
if (IsOrderNumberInUse(orderNumber, order) == true)
{
Console.WriteLine("Duplicate order number");
}
}
GetData(out customerName, out qtyOrdered);
order[x] = new Order(orderNumber, customerName, qtyOrdered);
}
Console.ReadLine();
}
//METHOD TO CHECK FOR DUPLICATES
private static bool IsOrderNumberInUse(int orderNumber, Order[] orders)
{
foreach (Order order in orders)
{
if (order.OrderNumber == orderNumber)
{
return true;
}
}
// If orderNumber was not found
return false;
}
static void GetData(out string customerName, out int qtyOrdered)
{
//Console.Write("Enter Order Number: ");
//int.TryParse(Console.ReadLine(), out orderNumber);
Console.Write("Enter Customer Name: ");
customerName = Console.ReadLine();
Console.Write("Enter Quantity Ordered: ");
int.TryParse(Console.ReadLine(), out qtyOrdered);
}
class Order
{
private const double PRICE = 19.95;
public int OrderNumber { get; set; }
public string CustomerName { get; set; }
public int QtyOrdered { get; set; }
public double totalPrice
{
get
{
return QtyOrdered * PRICE;
}
}
public Order(int orderNumber, string customer, int qty) // Constructor
{
OrderNumber = orderNumber;
CustomerName = customer;
QtyOrdered = qty;
}
public override string ToString()
{
return ("\n" + GetType() + "\nCustomer: " + CustomerName + "\nOrder Number: " + OrderNumber +
"\nQuantity: " + QtyOrdered + "\nTotal Order: " + totalPrice.ToString("C2"));
}
public override bool Equals(object x)
{
bool isEqual;
if (this.GetType() != x.GetType())
isEqual = false;
else
{
Order temp = (Order)x;
if (OrderNumber == temp.OrderNumber)
isEqual = true;
else
isEqual = false;
}
return isEqual;
}
public override int GetHashCode()
{
return OrderNumber;
}
}
}
I am trying not to use Lists as I have learned them yet and my next two exercises are connected to this one. I'm afraid if I use Lists, I will be even more lost. I am getting null errors and need help fixing them. Here is my code. Would using Equals be a better approach than the one that I am currently struggling with? Thank you for your patience...
class Program
{
static void Main()
{
Order [] orders = new Order [3];
int tempOrderNumber;
string tempCustomerName;
int tempQtyOrdered;
for (int x = 0; x < orders.Length; ++x) // fill list
{
tempOrderNumber = AskForOrderNumber(orders);
GetData(out tempCustomerName, out tempQtyOrdered);
orders[x] = new Order(tempOrderNumber, tempCustomerName, tempQtyOrdered);
}
Console.ReadLine();
}
private static int AskForOrderNumber(Order [] orders)
{
int tempOrderNumber;
Console.Write("Enter Order Number: ");
int.TryParse(Console.ReadLine(), out tempOrderNumber);
if (orders[0] !=null && IsOrderNumberInUse(tempOrderNumber, orders) == true) //Check for duplicates
{
Console.WriteLine("Duplicate order number");
AskForOrderNumber(orders);
}
return tempOrderNumber;
}
static void GetData(out string tempCustomerName, out int tempQtyOrdered)
{
Console.Write("Enter Customer Name: ");
tempCustomerName = Console.ReadLine();
Console.Write("Enter Quantity Ordered: ");
int.TryParse(Console.ReadLine(), out tempQtyOrdered);
}
private static bool IsOrderNumberInUse(int tempOrderNumber, Order[] orders)
{
foreach (Order order in orders)
{
if (order.OrderNumber == tempOrderNumber)
{
return true;
}
}
return false;
}
class Order
{
private const double PRICE = 19.95;
public int OrderNumber { get; set; }
public string CustomerName { get; set; }
public int QtyOrdered { get; set; }
public double totalPrice
{
get
{
return QtyOrdered * PRICE;
}
}
public override string ToString()
{
return ("\n" + GetType() + "\nCustomer: " + CustomerName + "\nOrder Number: " + OrderNumber +
"\nQuantity: " + QtyOrdered + "\nTotal Order: " + totalPrice.ToString("C2"));
}
public Order(int orderNumber, string customerName, int qtyOrdered)
{
OrderNumber = orderNumber;
CustomerName = customerName;
QtyOrdered = qtyOrdered;
}
public override bool Equals(Object x)
{
bool isEqual;
if(this.GetType() != x.GetType())
isEqual = false;
else
{
Order temp = (Order) x;
if(OrderNumber == temp.OrderNumber)
isEqual = true;
else
isEqual = false;
}
return isEqual;
}
public override int GetHashCode()
{
return OrderNumber;
}
}
}
To fix your problem, I would suggest you use a List<Order>, because lists are resizable I believe they will be a better choice here.
Your current method doesn't work because you don't create order[x] until after you check for it.
Using Lists/Fixed Code
You should instead use the temporary orderNumber, however because the array is empty, you can also get null errors (which can be fixed) when checking for the first time, because of this I would again recommend a List.
List<Order> orders = new List<Order>(); //Orders list
int orderNumber; //Temporary order number
string customerName; //Temporary customer name
int qtyOrdered; //Temporary quantity
for (int x = 0; x < 3; ++x) //Fill List
{
Console.Write("Enter Order Number: ");
int.TryParse(Console.ReadLine(), out orderNumber); //Parse order number
if (IsOrderNumberInUse(orderNumber, orders) == true) //Check for duplicates
{
Console.WriteLine("Duplicate order number");
}
//Get data and add to list
GetData(out customerName, out qtyOrdered);
orders.Add(new Order(orderNumber, customerName, qtyOrdered));
}
Console.ReadLine();
Asking the user again if input is invalid
The example above shows my suggestions to fix your problem and use a List, but if you would like to go further and prompt the user to re-enter the value of it is in use. You can do this by creating a method to ask the user for input, and through recursion, ask them again if in use.
...
for (int x = 0; x < 3; ++x) //Fill List
{
orderNumber = AskForOrderNumber(orders);
//Get data and add to list
GetData(out customerName, out qtyOrdered);
orders.Add(new Order(orderNumber, customerName, qtyOrdered));
}
Console.ReadLine();
}
private static int AskForOrderNumber(List<Order> orders)
{
int orderNumber;
Console.Write("Enter Order Number: ");
int.TryParse(Console.ReadLine(), out orderNumber); //Parse order number
if (IsOrderNumberInUse(orderNumber, orders) == true) //Check for duplicates
{
Console.WriteLine("Duplicate order number");
AskForOrderNumber(orders);
}
return orderNumber;
}
Better method for checking for validation
There is also nothing wrong with your current method for checking for duplicates, but it could be improved with LINQ. (using System.LINQ)
private static bool IsOrderNumberInUse(int orderNumber, List<Order> orders)
{
return orders.Any(o => o.OrderNumber == orderNumber);
}
Related
I have a simple inventory application which is a program which you can add, view and delete the product. Currently I had already finished the add function and view function but left only the delete function which I am unsure of. ( Main program case 3)
class Inventory
{
Product []items;
int maxSize;
int size;
public Inventory(int in_maxSize)
{
maxSize = in_maxSize;
size = 0;
items = new Product[maxSize];
}
public bool AddProduct(Product in_Product)
{
if(getSize()<maxSize)
{
items[size] = in_Product;
size++;
return true;
}
else
{
return false;
}
}
public int getSize()
{
return size;
}
public Product getProduct(int index)
{
return items[index];
}
}
}
here is my product class:
class Product
{
private string name;
private int itemNumber;
private int unitsInStock;
private double price;
private double value;
public Product()
{
}
public Product(string in_name, int in_itemNumber, int in_unitsInStock, double in_price)
{
name = in_name;
itemNumber = in_itemNumber;
unitsInStock = in_unitsInStock;
price = in_price;
}
public double getValueOfInventory()
{
value = unitsInStock * price;
return this.value;
}
public int getItemNumber()
{
return this.itemNumber;
}
public string getName()
{
return this.name;
}
public int getUnitsInStock()
{
return this.unitsInStock;
}
public double getPrice()
{
return this.price;
}
public void setItemNumber(int in_itemNumber)
{
itemNumber = in_itemNumber;
}
public void setName(string in_name)
{
name = in_name;
}
public void setUnitsInStock(int in_unitsInStock)
{
unitsInStock = in_unitsInStock;
}
public void setPrice(double in_price)
{
price = in_price;
}
}
}
Here is my main program:
class Program
{
static void Main(string[] args)
{
Inventory myInventory = new Inventory(100);
Product myProduct = new Product();
myProduct.setItemNumber(1000);
myProduct.setName("Pen");
myProduct.setPrice(1.25);
myProduct.setUnitsInStock(50);
myInventory.AddProduct(myProduct);
Product myProduct1 = new Product("Paper", 2000, 5000, 12.85);
myInventory.AddProduct(myProduct1);
Product tempProduct;
int x = 0;
do
{
Console.WriteLine("1.Add product");
Console.WriteLine("2.View product");
Console.WriteLine("3.Delete product");
Console.WriteLine("4.Exit the Application");
Console.WriteLine("------------------");
x = Convert.ToInt32(Console.ReadLine());
switch (x)
{
case 1:
Console.Write("Item number\t\t:");
int a=Convert.ToInt32(Console.ReadLine());
Console.Write("Name\t\t\t:");
string b=Convert.ToString(Console.ReadLine());
Console.Write("Price\t\t\t:");
double c=Convert.ToDouble(Console.ReadLine());
Console.Write("Units in stocks\t\t:");
int d=Convert.ToInt32(Console.ReadLine());
Product myProduct2 = new Product(b,a,d,c);
myInventory.AddProduct(myProduct2);
// Product myProduct1 = new Product("Paper", 2000, 5000, 12.85);
// myInventory.AddProduct(myProduct1);
/*Console.Write("Item number\t\t:");
ItemNo = Convert.ToInt32(Console.ReadLine());
Console.Write("Name\t\t\t:");
Name = Convert.ToString(Console.ReadLine());
Console.Write("Price\t\t\t:");
Price = Convert.ToDouble(Console.ReadLine());
Console.Write("Units in stocks\t\t:");
UnitsInStocks = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("------------------");*/
break;
case 2:
for (int i = 0; i < myInventory.getSize(); i++)
{
tempProduct = myInventory.getProduct(i);
Console.WriteLine("Item number\t\t:" + tempProduct.getItemNumber());
Console.WriteLine("Name\t\t\t:" + tempProduct.getName());
Console.WriteLine("Price\t\t\t:" + tempProduct.getPrice());
Console.WriteLine("Units in stocks\t\t:" + tempProduct.getUnitsInStock());
Console.WriteLine("------------------");
}
break;
case 3:
int j;
Console.WriteLine("Please enter the item id for the items that you want to delete");
j = Convert.ToInt32(Console.ReadLine());
if (j == a)
{
break;
case 4:
Environment.Exit(0);
break;
default:
break;
}
}
while (x != 4);
}
}
}
In my main program, i left case 3 undone as that is the delete function part,
How can I accomplish this?
This is the simple way. Replace your array with a List of products:
class Inventory
{
List<Product> items;
int maxSize;
public Inventory(int in_maxSize)
{
maxSize = in_maxSize;
items = new List<Product>();
}
public bool AddProduct(Product in_Product)
{
if(items.Count < maxSize)
{
items.Add(in_Product);
return true;
}
else
{
return false;
}
}
public Product getProduct(int index)
{
return items[index];
}
public void removeProduct(int index)
{
items.removeAt(index);
}
}
In your switch call removeProduct method to delete the product at position that you pass.
I am creating a program that intakes info for the number of visits on separate days to a centre. I am using an array to keep track of that info, but I also need to create a method that calls up the day with the least number of visits and then displays it in an output.
class ScienceCentreVisitation
{
private string centreName;
private string city;
private decimal ticketPrice;
private string[] visitDate;
private int[] adultVisitors;
private decimal[] totalRevenue;
//constructors
public ScienceCentreVisitation()
{
}
public ScienceCentreVisitation(string cent)
{
centreName = cent;
}
public ScienceCentreVisitation(string cent, string cit, decimal price, string[] date, int[] visit, decimal[] rev)
{
visitDate = new string[date.Length];
adultVisitors = new int[visit.Length];
totalRevenue = new decimal[rev.Length];
Array.Copy(date, 0, visitDate, 0, date.Length);
Array.Copy(visit, 0, adultVisitors, 0, adultVisitors.Length);
Array.Copy(rev, 0, totalRevenue, 0, rev.Length);
centreName = cent;
city = cit;
ticketPrice = price;
}
//properties
public string CentreName
{
get
{
return centreName;
}
set
{
centreName = value;
}
}
public string City
{
get
{
return city;
}
set
{
city = value;
}
}
public decimal TicketPrice
{
get
{
return ticketPrice;
}
set
{
ticketPrice = value;
}
}
public string[] VisitDate
{
get
{
return visitDate;
}
set
{
visitDate = value;
}
}
public int[] AdultVisitors
{
get
{
return adultVisitors;
}
set
{
adultVisitors = value;
}
}
public decimal[] TotalRevenue
{
get
{
return totalRevenue;
}
set
{
totalRevenue = value;
}
}
//methods
public decimal CalculateTotalRevenue()
{
decimal totalRev;
int cntOfValidEntries;
int total = 0;
foreach (int c in adultVisitors)
total += c;
cntOfValidEntries = TestForZeros();
totalRev = (decimal)total / cntOfValidEntries;
return totalRev;
}
public int TestForZeros()
{
int numberOfTrueVisits = 0;
foreach (int cnt in adultVisitors)
if (cnt != 0)
numberOfTrueVisits++;
return numberOfTrueVisits;
}
public int GetIndexOfLeastVisited()
{
int minVisIndex = 0;
for (int i = 1; i < adultVisitors.Length; i++)
if (adultVisitors[i] < adultVisitors[minVisIndex])
minVisIndex = i;
return minVisIndex;
}
public int GetLeastVisited()
{
return adultVisitors[GetIndexOfLeastVisited()];
}
public string GetDateWithLeastVisited()
{
return visitDate[GetIndexOfLeastVisited()];
}
public int GetIndexOfMostRevenue()
{
int maxRevIndex = 0;
for (int i = 1; i < totalRevenue.Length; i++)
if (totalRevenue[i] > totalRevenue[maxRevIndex])
maxRevIndex = i;
return maxRevIndex;
}
public decimal GetMostRevenue()
{
return totalRevenue[GetIndexOfMostRevenue()];
}
public string GetDateWithMostRevenue()
{
return visitDate[GetIndexOfMostRevenue()];
}
public override string ToString()
{
return "Name of Centre: " + centreName +
"\nCity: " + city +
"\n Price of ticket: " + ticketPrice +
"\nDate of Least One-Day Adult Visitors:\t\t" + GetDateWithLeastVisited() +
"\nNumber of Least One-Day Adult Visitors:\t\t" + GetLeastVisited() +
"\nDate of Most Total Revenue Collected:\t\t" + GetDateWithMostRevenue() +
"\nHighest Total Revenue Collected:\t\t" + GetMostRevenue();
}
}
Other class:
class ScienceCentreApp
{
static void Main(string[] args)
{
string centreName;
string city;
decimal ticketPrice = 0;
int visitorCnt;
string[] dArray = new String[5];
int[] adultVisitors = new int[5];
decimal[] totalRevenue = new decimal[5];
char enterMoreData = 'Y';
ScienceCentreVisitation scv;
do
{
visitorCnt = GetData(out centreName, out city, out ticketPrice, dArray, adultVisitors, totalRevenue);
scv = new ScienceCentreVisitation(centreName, city, ticketPrice, dArray, adultVisitors, totalRevenue);
Console.Clear();
Console.WriteLine(scv);
Console.Write("\n\n\n\nDo you want to enter more data - " +
"(Enter y or n)? ");
if (char.TryParse(Console.ReadLine(), out enterMoreData) == false)
Console.WriteLine("Invalid data entered - " +
"No recorded for your respones");
} while (enterMoreData == 'y' || enterMoreData == 'y');
Console.ReadKey();
}
public static int GetData(out string centreName, out string city, out decimal ticketPrice, string[] dArray, int[] adultVisitors, decimal[] totalRevenue)
{
int i,
loopCnt;
Console.Clear();
Console.Write("Name of Centre: ");
centreName = Console.ReadLine();
Console.Write("City: ");
city = Console.ReadLine();
Console.Write("Ticket Price: ");
string inValue = Console.ReadLine();
ticketPrice = Convert.ToDecimal(inValue);
Console.Write("How many records for {0}? ", centreName);
string inValue1 = Console.ReadLine();
if (int.TryParse(inValue1, out loopCnt) == false)
Console.WriteLine("Invalid data entered - " +
"0 recorded for number of records");
for (i = 0; i < loopCnt; i++)
{
Console.Write("\nDate (mm/dd/yyyy): ");
dArray[i] = Console.ReadLine();
if (dArray[i] == "")
{
Console.WriteLine("No date entered - " +
"Unknown recorded for visits");
dArray[i] = "Unknown";
}
Console.Write("Number of One-Day Adult Visitors: ");
inValue1 = Console.ReadLine();
if (int.TryParse(inValue1, out adultVisitors[i]) == false)
Console.WriteLine("Invalid data entered - " +
"0 recorded for adults visited");
}
return i;
}
}
I had it working before I made some changes to my program, but now it keeps coming up blank when I run it. Any idea why?
Without having the complete code it's difficult to debug this for you.
But here's a suggestion that came up when I was reading the start of your question:
It seems like the basic gist would be to use a Dictionary<DateTime, int> which would store the number of visits for each day.
Then you can use a simple LINQ query to get the smallest value:
dictionary.OrderBy(kvp => kvp.Value).First()
Of course, you can use a complex class in place of the int and store more data (location, price of admission for that day, adult visits, etc.).
class CenterVisitations
{
internal int Visitations { get; set; }
internal decimal TicketPrice { get; set; }
internal string Location { get; set; }
//add other stuff here, possibly create another class
//to store TicketPrice, Location and other static center data
//and create a reference to that here, instead of the above
//TicketPrice and Location...
}
Then you can define your dictionary like so:
Dictionary<DateTime, CenterVisitations>
And query it almost the same was as last time:
dictionary.Order(kvp => kvp.Value.Visitations).First();
Sorting and selecting would work the same way. Additionally you could add a .Where query to set a range of dates which you want to check:
dictionary.Where(kvp => kvp.Key < DateTime.Today && kvp.Key > DateTime.Today.AddDays(-7)) will only look for the last weeks worth of data.
It also seems you're keeping your data in separate arrays, which means querying it is that much harder. Finally, consider converting dates into DateTime objects rather than strings.
So I'm drawing a blank on this error.
Failed to compare two elements in the array.
The Array.Sort(patient); is where the error is accruing. I do have a IComparable interface, and a class file with the following code: Trying to sort by patient ID number
class Patient : IComparable
{
private int patientID;
private string patientName;
private int patientAge;
private decimal amount;
public int PatientId { get; set; }
public string PatientName { get; set; }
public int PatientAge { get; set; }
public decimal PatientAmount { get; set; }
int IComparable.CompareTo(Object o)
{
int value;
Patient temp = (Patient)o;
if (this.PatientId > temp.PatientId)
value = 1;
else if (this.PatientId < temp.PatientId)
value = -1;
else
value = 0;
return value;
}
}
and this is what's in my main method. Didn't add the Display() cause nothing added to it now, why it's commented out
private static void Main(string[] args)
{
int numOfPatients =2 ;
Patient[] patient = new Patient[numOfPatients];
for (int x = 0; x < numOfPatients; x++)
{
int intvalue;
decimal dollarValue;
patient[x] = new Patient();
Console.Write("Patient {0}: ", (x + 1));
Console.WriteLine("Enter the Patients ID: ");
bool isNum = int.TryParse(Console.ReadLine(), out intvalue);
if (isNum)
{
patient[x].PatientId = intvalue;
}
else
{
Console.WriteLine("Patient ID was invalid. ID needs to be numbers");
Console.WriteLine("Enter the Patients ID: ");
int.TryParse(Console.ReadLine(), out intvalue);
}
Console.WriteLine("Enter the Patients Name: ");
patient[x].PatientName = Console.ReadLine();
Console.WriteLine("Enter the Patients Age: ");
bool isAge = int.TryParse(Console.ReadLine(), out intvalue);
if (isAge)
{
patient[x].PatientAge = intvalue;
}
else
{
Console.WriteLine("Patient Age was invalid. Age needs to be numbers");
Console.WriteLine("Enter the Patients Age: ");
int.TryParse(Console.ReadLine(), out intvalue);
}
Console.WriteLine("Enter the Patients Amount Due: ");
bool isAmount = Decimal.TryParse(Console.ReadLine(), out dollarValue);
if (isAmount)
{
patient[x].PatientAmount = dollarValue;
}
else
{
Console.WriteLine("Patient amount Due was invalid. Amount needs to be a numbers");
Console.WriteLine("Enter the Patients Amount Due: ");
int.TryParse(Console.ReadLine(), out intvalue);
}
}
Array.Sort(patient);
Console.WriteLine("Patients in order with Amounts Owed are: ");
for (int i = 0; i < patient.Length; ++i) ;
//Display(patient[i], numOfPatients);
A few things come to mind:
a) Why not implement IComparable<Patient>?
b) Why re-implement int.CompareTo(int)? Your implementation of IComparable could just return this.PatientID.CompareTo(other.PatientID).
c) Are you sure the array is full when you're sorting it? I'm not sure what would happen if it contains null.
I would just write
return this.PatientId.CompareTo(temp.PatientId)
inside the overriden CompareTo method the class. No need to use equality symbols. This will do the int compare for you and return the correct value.
I also suggest that you just use some implementation of the IList class, and then you can use LinQ statements. Using this will prevent there ever being a null value in the "array"
It looks like if Array.Sort is passed with a typed array would call the Array.Sort<T>(T[]) overload. According to the MSDN documentation, this overload uses the IComparable<T> interface to compare objects. So it looks like you have two choices:
You can implement IComparable<T> instead of IComparable (better).
You could cast your array to Array to call the Array.Sort(Array) overload which uses the IComparable interface (worse).
In my code below, it is supposed to do the following tasks:
Prompt the user for values for each Order. Do not allow duplicate order numbers; force the user to reenter the order when a duplicate order number is entered. When five valid orders have been entered, display them all, plus a total of all orders.
The problem is that there are errors in it. I tried to solve the errors by myself but I can't fix it. I've been stuck in these errors for many hours. And another thing, I can't really understand why does it displays that OrderDemo does not contain a definition for Total, OrderNumber, Customer and Quantity. Any help given would be very much appreciated. Thanks!
using System;
class OrderDemo
{
public static void Main()
{
OrderDemo[] order = new OrderDemo[5];
int x, y;
double grandTotal = 0;
bool goodNum;
for (x = 0; x < order.Length; ++x)
{
order[x] = new Order(); //OrderDemo.Order does not contain a constructor that takes 0 arguments
Console.Write("Enter order number");
order[x].OrderNumber = Convert.ToInt32(Console.ReadLine());
goodNum = true;
for (y = 0; y < x; ++y)
{
if (order[x].Equals(order[y]))
goodNum = false;
}
while (!goodNum)
{
Console.Write("sorry, the order number " + order[x].OrderNumber + "is a duplicate. " + "\nPlease reenter: ");
order[x].OrderNumber = Convert.ToInt32(Console.ReadLine());//OrderDemo does not contain a definition for OrderNumber and no extension..
goodNum = true;
for (y = 0; y > x; ++y)
{
if (order[x].Equals(order[y]))
goodNum = false;
}
}
Console.Write("Enter customer name");
order[x].Customer = Console.ReadLine();//OrderDemo does not contain a definition for Customer and no extension..
Console.Write("Enter Quantity");
order[x].Quantity = Convert.ToInt32(Console.ReadLine());//OrderDemo does not contain a definition for Quantity and no extension..
}
Console.WriteLine("\nSummary\n");
for (x = 0; x < order.Length; ++x)
{
Console.WriteLine(order[x].ToString());
grandTotal += order[x].Total; //OrderDemo does not contain a definition for Total and no extension..
}
Console.WriteLine(" Total for all orders is" + grandTotal.ToString("c"));
}
public class Order
{
public int orderNum;
public string cusName;
public int quantity;
public double total;
public const double ItemPrice = 19.95;
public Order(int ordNum, string cusName, int numOrdered)
{
OrderNum = ordNum;
Customer = cusName;
Quantity = numOrdered;
}
public int OrderNum
{
get { return orderNum; }
set { orderNum = value; }
}
public string Customer
{
get { return cusName; }
set { cusName = value; }
}
public int Quantity
{
get
{
return quantity;
}
set
{
quantity = value;
total = quantity * ItemPrice;
}
}
public double Total
{
get
{
return total;
}
}
public override string ToString()
{
return ("Order " + OrderNum + " " + Customer + " " + Quantity +
" #Php" + ItemPrice.ToString("0.00") + " each. " + "The total is Php" + Total.ToString("0.00"));
}
public override bool Equals(Object e)
{
bool equal;
Order temp = (Order)e;
if (OrderNum == temp.OrderNum)
equal = true;
else
equal = false;
return equal;
}
public override int GetHashCode()
{
return OrderNum;
}
}
}
You declared your array as containing OrderDemo objects.
As the error clearly states, OrderDemo doesn't have any properties.
You probably mean Order, which is a different class.
C# provides a default constructor for you, as long as you don't define other constructors which accept parameters. Because you have this:
public Order(int ordNum, string cusName, int numOrdered)
{
OrderNum = ordNum;
Customer = cusName;
Quantity = numOrdered;
}
The default constructor isn't generated. You need to add this:
public Order() { }
...if you want to create objects without passing parameters to it.
Also, as SLaks has pointed out, you have declared your array incorrectly:
OrderDemo[] order = new OrderDemo[5];
Should be this instead:
var order = new Order[5]; // or Order[] order = new Order[5];
My code below works fine but what I want to do is to display the summary in ascending order according to its OrderNum. I tried to put Array.Sort(order[x].OrderNum) but error cannot convert from int to System.Array. Any suggestions on how I can sort this? Thank you very much!
using System;
class ShippedOrder
{
public static void Main()
{
Order[] order = new Order[5];
int x, y;
double grandTotal = 0;
bool goodNum;
for (x = 0; x < order.Length; ++x)
{
order[x] = new Order();
Console.Write("Enter order number: ");
order[x].OrderNum = Convert.ToInt32(Console.ReadLine());
goodNum = true;
for (y = 0; y < x; ++y)
{
if (order[x].Equals(order[y]))
goodNum = false;
}
while (!goodNum)
{
Console.Write("Sorry, the order number " + order[x].OrderNum + " is a duplicate. " + "\nPlease re-enter: ");
order[x].OrderNum = Convert.ToInt32(Console.ReadLine());
goodNum = true;
for (y = 0; y > x; ++y)
{
if (order[x].Equals(order[y]))
goodNum = false;
}
}
Console.Write("Enter customer name: ");
order[x].Customer = Console.ReadLine();
Console.Write("Enter Quantity: ");
order[x].Quantity = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("\nSummary:\n");
for (x = 0; x < order.Length; ++x)
{
Array.Sort(order[x].OrderNum); //This line is where the error is located
Console.WriteLine(order[x].ToString());
grandTotal += order[x].Total;
}
Console.WriteLine("\nTotal for all orders is Php" + grandTotal.ToString("0.00"));
Console.Read();
}
public class Order
{
public int orderNum;
public string cusName;
public int quantity;
public double total;
public const double ItemPrice = 19.95;
public Order() { }
public Order(int ordNum, string cusName, int numOrdered)
{
OrderNum = ordNum;
Customer = cusName;
Quantity = numOrdered;
}
public int OrderNum
{
get { return orderNum; }
set { orderNum = value; }
}
public string Customer
{
get { return cusName; }
set { cusName = value; }
}
public int Quantity
{
get
{
return quantity;
}
set
{
quantity = value;
total = quantity * ItemPrice + 4;
}
}
public double Total
{
get
{
return total;
}
}
public override string ToString()
{
return ("ShippedOrder " + OrderNum + " " + Customer + " " + Quantity +
" #Php" + ItemPrice.ToString("0.00") + " each. " + "Shipping is Php4.00\n" + " The total is Php" + Total.ToString("0.00"));
}
public override bool Equals(Object e)
{
bool equal;
Order temp = (Order)e;
if (OrderNum == temp.OrderNum)
equal = true;
else
equal = false;
return equal;
}
public override int GetHashCode()
{
return OrderNum;
}
}
}
Just use Linq:
order = order.OrderBy(x => x.OrderNum).ToArray();
While looking this link, found that Array.Sort will not take integer as parameter.
You have to pass all the data as Array object.
Try the following:
order.Sort( delegate (Order o1, Order o2) {
return o1.OrderNum.CompareTo(o2.OrderNum);
});