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.
Related
I'm trying to use the keyword value in the set accessor and as long as the user entered value is greater than 0, I want to set it to the variable Quantity.
I can not seem to find what it is I am doing wrong. I keep getting a traceback error to for this Quantity = value;. Hoping someone can see what I don't. Thanks.
using System;
namespace Invoice
{
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("How many parts would you like to " +
"enter into the system: ");
int newParts = int.Parse(Console.ReadLine());
Invoice[] invoice = new Invoice[newParts];
for (int i = 0; i < newParts; i++)
{
invoice[i] = new Invoice();
Console.WriteLine("Enter the part number: ");
invoice[i].PartNumber = Console.ReadLine();
Console.WriteLine("Enter description of item: ");
invoice[i].PartDescription = Console.ReadLine();
Console.WriteLine("Enter the quantity: ");
invoice[i].Quantity = int.Parse(Console.ReadLine());
Console.WriteLine("Enter in the price of the item: ");
invoice[i].PricePerItem = decimal.Parse(Console.ReadLine());
}
for (int i = 0; i < newParts; i++)
{
invoice[i].DisplayOrder();
}
}
}
}
using System;
namespace Invoice
{
public class Invoice
{
public string PartNumber { get; set; }
public string PartDescription { get; set; }
public int Quantity
{
get { return Quantity; }
set
{
if (value >= 0)
{
Quantity = value;
}
if (value <= 0)
{
Quantity = Quantity;
}
}
}
public decimal PricePerItem
{
get
{
return PricePerItem;
}
set
{
if(value >= 0.0m)
{
PricePerItem = value;
}
if (value <= 0.0m)
{
PricePerItem = PricePerItem;
}
}
}
public Invoice(String PartNumber, String PartDescription, int Quantity, decimal PricePerItem)
{
this.PartNumber = PartNumber;
this.PartDescription = PartDescription;
this.Quantity = Quantity;
this.PricePerItem = PricePerItem;
}
public Invoice()
{
}
public decimal GetInvoiceAmount(int numberOfItems, decimal priceOfItem)
{
return numberOfItems * priceOfItem;
}
public void DisplayOrder()
{
decimal total = GetInvoiceAmount(Quantity, PricePerItem);
// Display Receipt
Console.Write("\nOrder Receipt: ");
Console.WriteLine($"\nPart Number: {PartNumber}");
Console.WriteLine($"Unit Price: {PricePerItem:C}");
Console.WriteLine($"Quantity: {Quantity}");
Console.WriteLine($"Part Description: {PartDescription}");
Console.WriteLine($"Total price: {total:C}");
}
}
}
This makes no sense:
if (value >= 0)
{
Quantity = value;
}
if (value <= 0)
{
Quantity = Quantity;
}
Why would you set a property to itself? That can't achieve anything useful. You say that you want to set the property if and only if the assigned value is greater than zero, so why would you be checking value for anything but being greater than zero?
if (value > 0)
{
Quantity = value;
}
That's it, that's all.
That said, you also ought to be throwing an ArgumentOutOfRangeException if the value is not valid, rather than just silently not setting the property. The logical way to do that would be like so:
if (value <= 0)
{
throw new ArgumentOutOfRangeException(...);
}
Quantity = value;
Now the property value will only be set if an exception is not thrown.
I also just realised that you have no backing field for this property, so that's wrong. The whole thing should look like this:
private int quantity;
public int Quantity
{
get { return quantity; }
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(...);
}
quantity = value;
}
}
The error is because in your set {} you are invoking the same setter recursively.
private int quantity;
public int Quantity
{
get { return this.quantity; }
set
{
if (value >= 0)
{
this.quantity= value;
}
}
}
private decimal pricePerItem;
public decimal PricePerItem
{
get
{
return this.pricePerItem;
}
set
{
if(value >= 0.0m)
{
this.pricePerItem= value;
}
}
}
I have an array that is populated with user input and needs to be sorted according to a particular property. I have looked at similar questions on here but it does not seem to help my specific situation and so far nothing I've tried has worked.
The properties for the array are defined in a separate class.
It's a basic program for loading employees onto a system and the output needs to be sorted according to their salary.
*Note that I am a student and I am possibly missing something very basic.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
using System.Threading.Tasks;
namespace Instantiating_Objects
{
class Program
{
static void Main(string[] args)
{
//Cleaner cleaner = new Cleaner(); // Instantiantion
// Object Array
Cleaner[] clean = new Cleaner[3]; // Empty Object Array
Cleaner[] loadedCleaners = LoadCleaners(clean);
for (int i = 0; i < loadedCleaners.Length; i++)
{
Console.WriteLine(" ");
Console.WriteLine(loadedCleaners[i].Display() + "\n Salary: R" + loadedCleaners[i].CalcSalary());
}
Console.ReadKey();
}
public static Cleaner[] LoadCleaners(Cleaner[] cleaner)
{
for (int i = 0; i < cleaner.Length; i++)
{
Console.WriteLine("Enter your staff number");
long id = Convert.ToInt64(Console.ReadLine());
Console.WriteLine("Enter your last name");
string lname = Console.ReadLine();
Console.WriteLine("Enter your first name");
string fname = Console.ReadLine();
Console.WriteLine("Enter your contact number");
int contact = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter your number of hours worked");
int hours = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("");
// Populating object array
cleaner[i] = new Cleaner(id, fname, lname, contact, hours);
}
Array.Sort(, )
return cleaner;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Instantiating_Objects
{
class Cleaner
{
private long staffNo;
private string lastName;
private string fName;
private int contact;
private int noHours;
private double rate = 380.00;
public Cleaner() { }
public Cleaner(long staffId, string name, string surname, int number, int hours)
{
this.contact = number;
this.fName = surname;
this.lastName = name;
this.staffNo = staffId;
this.noHours = hours;
}
public int GetHours() { return noHours;}
public long GetStaffID() { return staffNo; }
public string GetSurname() { return lastName; }
public string GetName() { return fName; }
public int GetNumber() { return contact; }
// Calculate Salary
public double CalcSalary()
{
double salary = 0;
if(GetHours() > 0 && GetHours() <= 50)
{
salary = GetHours() * rate;
}
else if (GetHours() > 50)
{
salary = (GetHours() * rate) + 5000;
}
return salary;
}
public string Display()
{
return "\n Staff no: " + GetStaffID() + "\n Surname" + GetSurname()
+ "\n Name: " + GetName() + "\n Contact no: " + GetNumber();
}
}
}
I will combine Legacy code and Ňɏssa Pøngjǣrdenlarp into one.
First thing as Ňɏssa Pøngjǣrdenlarp said your Cleaner class has no properties.
I removed all your methods and changed it with properties instead
public class Cleaner
{
public Cleaner(long staffId, string name, string surname, int number, int hours)
{
StaffNo = staffId;
FName = name;
LastName = surname;
Contact = number;
NoHours = hours;
}
public long StaffNo { get; set; }
public string LastName { get; set; }
public string FName { get; set; }
public int Contact { get; set; }
public int NoHours { get; set; }
public double Rate => 380.00;
public double Salary
{
get
{
double salary = 0;
if (NoHours > 0 && NoHours <= 50)
{
salary = NoHours * Rate;
}
else if (NoHours > 50)
{
salary = (NoHours * Rate) + 5000;
}
return salary;
}
}
public override string ToString()
{
return "\n Staff no: " + StaffNo + "\n Surname" + LastName
+ "\n Name: " + FName + "\n Contact no: " + Contact;
}
}
Now that we have fixed the class we can look at the Program Main method.
Because we changed the cleaner class to use properties instead we can easily use Linq to orderby
private static void Main(string[] args)
{
//Cleaner cleaner = new Cleaner(); // Instantiantion
// Object Array
var clean = new Cleaner[3]; // Empty Object Array
var loadedCleaners = LoadCleaners(clean).OrderBy(_ => _.Salary).ToArray();
foreach (Cleaner v in loadedCleaners)
{
Console.WriteLine(" ");
Console.WriteLine(v + "\n Salary: R" + v.Salary);
}
Console.ReadKey();
}
You will notice that on this line
var loadedCleaners = LoadCleaners(clean).OrderBy(_ => _.Salary).ToArray();
that i am using Linq to order the Salary.
For more on Linq check out the following docs https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/
On a side note
I would say consistency is key, this will keep your code clean.
Look at the following example, the naming convention is inconsistent
public Cleaner(long staffId, string name, string surname, int number, int hours)
{
StaffNo = staffId;
FName = name;
LastName = surname;
Contact = number;
NoHours = hours;
}
Nice, clean and easy to follow
public Cleaner(long staffId, string firstName, string lastName, int number, int hours)
{
StaffId = staffId;
FirstName = firstName;
LastName = lastName;
Number = number;
Hours = hours;
}
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);
}
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);
});