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];
Related
This question already has answers here:
Field modifyDate is never assigned to, and will always have its default value 0
(1 answer)
Field is never assigned to and will always have its default value 0
(4 answers)
Closed 2 years ago.
I am having a couple problems with my block of code. Everything is working how it should be but my total is always 0. The warning description at the bottom of my screen says as follows: " 'Order.Total' is never assigned to, and will always have its default value 0".
How do I fix this warning sign?
I am also receiving a warning saying that my EqualsTo() statement is being overriden but not Object.GetHashCode(). How do I fix these 2 minor errors?
I'll give the entire code if you want to put it into your IDE and try debugging it your self...I'll also just paste a portion of the code I think that is creating the issue for the final total always defaulting to 0.
ENTIRE CODE
using System;
namespace Order
{
class Program
{
static void Main(string[] args)
{
// creating the orders
Order order1 = new Order(1, "Joe Bob", 2);
Order order2 = new Order(3, "Sally Bob", 4);
Order order3 = new Order(1, "Jimmy Bob", 5);
Console.WriteLine(order1.ToString() + "\n");
Console.WriteLine(order2.ToString() + "\n");
Console.WriteLine(order3.ToString() + "\n");
//checks for duplicates
CheckDuplicate(order1, order2);
CheckDuplicate(order2, order3);
CheckDuplicate(order1, order3);
}
// output for duplicates
public static void CheckDuplicate(Order firstOrder, Order secondOrder)
{
if (firstOrder.Equals(secondOrder))
{
Console.WriteLine("The two orders are the same!");
}
else
{
Console.WriteLine("The two orders are not the same!");
}
}
}
class Order
{
// setting properties
double itemPrice = 12.35;
public int OrderNum { get; set; }
public string CustomerName { get; set; }
public double Quantity;
private readonly double Total;
// total price
public double GetTotal()
{
double Total = Quantity * itemPrice;
return Total;
}
// equals to method
public override bool Equals(Object o)
{
bool isEqual = true;
if (this.GetType() != o.GetType())
isEqual = false;
else
{
Order temp = (Order)o;
if (OrderNum == temp.OrderNum)
isEqual = true;
else
isEqual = false;
}
return isEqual;
}
// default constructor
public Order(int OrderNum, string CustomerName, double Quantity)
{
this.OrderNum = OrderNum;
this.CustomerName = CustomerName;
this.Quantity = Quantity;
}
// returns final output
public override string ToString()
{
return ("Order Number : " + OrderNum) + "\n" + ("Customer name : " + CustomerName) + "\n" + ("Quantity Ordered : " + Quantity) + "\n" + ("Totatl Price : " + Total);
}
}
}
PORTION OF CODE FOR WARNING
class Order
{
// setting properties
double itemPrice = 12.35;
public int OrderNum { get; set; }
public string CustomerName { get; set; }
public double Quantity;
private readonly double Total;
// total price
public double GetTotal()
{
double Total = Quantity * itemPrice;
return Total;
}
// equals to method
public override bool Equals(Object o)
{
bool isEqual = true;
if (this.GetType() != o.GetType())
isEqual = false;
else
{
Order temp = (Order)o;
if (OrderNum == temp.OrderNum)
isEqual = true;
else
isEqual = false;
}
return isEqual;
}
// default constructor
public Order(int OrderNum, string CustomerName, double Quantity)
{
this.OrderNum = OrderNum;
this.CustomerName = CustomerName;
this.Quantity = Quantity;
}
// returns final output
public override string ToString()
{
return ("Order Number : " + OrderNum) + "\n" + ("Customer name : " + CustomerName) + "\n" + ("Quantity Ordered : " + Quantity) + "\n" + ("Totatl Price : " + Total);
}
}
As the comments indicate, nothing is calling GetTotal() to assign the value to Total.
If you don't want to call GetTotal, you can put that formula in the constructor and assign the Total value at that time.
In my code I was instructed to return an object in my GetCustomer method in my CustomerManager class from the Customer class . I am new to object oriented programming so I don't have any ideas on how to do this. Can someone help me out?
Customer Manager Class
public class customerManager
{
private static int currentCusNo;
private int maxCustomers;
private int numCustomers;
customer[] cList;
public customerManager(int maxCust, int seed)
{
currentCusNo = seed;
maxCustomers = maxCust;
numCustomers = 0;
cList = new customer[maxCustomers];
}
public bool addcustomers(string fN, string lN, string ph)
{
if (numCustomers > maxCustomers) return false;
customer m = new customer(fN, lN, ph, currentCusNo);
currentCusNo++;
cList[numCustomers] = m;
numCustomers++;
return true;
}
public int findCustomer(int cusID)
{
for (int x = 0; x < numCustomers; x++)
{
if (cList[x].getID() == cusID)
{
return x;
}
}
return -1;
}
public bool customerExist(int cusID)
{
for (int x = 0; x < numCustomers; x++)
{
if (cList[x].getID() == cusID)
{
return true;
}
}
return false;
}
public string customerlist()
{
string y = " ";
for (int x = 0; x < numCustomers; x++)
{
y += "\nFirst Name: " + cList[x].getFirstName() + "\nLast name: " + cList[x].getLasttName() + "\nCustomer ID: " + cList[x].getID();
}
return y;
}
public customer GetCustomer(int cID)
{
for (int x = 0; x < numCustomers; x++)
{
}
}
}
Customer Class
public class customer
{
private int customerID;
private string firstName;
private string lastName;
private string phone;
public customer(string fN, string lN, string ph, int cId)
{
customerID = cId;
firstName = fN;
lastName = lN;
phone = ph;
}
public int getID() { return customerID; }
public string getFirstName() { return firstName; }
public string getLasttName() { return lastName; }
public string getPhone() { return phone; }
public string toString()
{
string s = "";
s +="First Name: " + firstName + "\nLast Name: " + lastName + "\nPhone: " + phone + "\nCustomer ID: " + customerID;
return s;
}
}
When someone says "return an object" in C# they typically mean: "return a reference to the thing I want". Luckily, classes are always stored (at least, for purposes for this discussion) as references already, so this is really simple.
The code will be nearly identical to your findCustomer method but instead of returning the index of the customer, it will just return the customer reference.
public customer GetCustomer(int cID)
{
for (int x = 0; x < numCustomers; x++)
{
customer testCustomer = cList[x];
if (testCustomer.getID() == cusID)
{
return testCustomer;
}
}
return null;
}
I explicitly put the testCustomer variable in so that
You would see that cList is an array of customers and you can pull their references out.
Its slightly more efficient to not get the item out of the array twice. If this wasn't constant time the efficiency gain would be more important.
And finally a few helpful hints:
Classes in C# should be PascalCase (Customer)
Multiple returns should be done with care, as they can be confusing to read
Having manual get methods for data is unusual in C#, typically they are just exposed via properties
It looks like it would be very similar to your findCustomer method, only that instead of returning an int, you would return the actual cutomer object. If I followed the same pattern of the rest of your class, it would look something like:
public customer GetCustomer(int cID)
{
for (int x = 0; x < numCustomers; x++)
{
if (cList[x].getID() == cID)
{
return cList[x];
}
}
return null;
}
It should be said, however, that if you are using System.Linq, then the same method could be done with just one line:
public customer GetCustomer(int cID)
{
return cList.Where(x => x.getID() == cID).SingleOrDefault();
}
Cheers
JM
Using your code...
Find the index of the cID you want and return the item of the list in this index or null if you do not find.
public customer GetCustomer(int cID)
{
var index = findCustomer(cID);
return index == -1 ? null : cList[index];
}
Or ...
Copy and paste the findCustomer code, changing return x; by return cList[x]; and -1 to null;
public customer GetCustomer(int cID)
{
for (var x = 0; x < numCustomers; x++)
if (cList[x].getID() == cID)
return cList[x];
return null;
}
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.
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);
}
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);
});