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).
Related
namespace HW
{
class Program
{
struct Employee
{
int join_year;
int age;
string dept;
public void getval(int join_year, int age, string dept)
{
this.join_year = join_year;
this.age = age;
this.dept = dept;
}
public void showval()
{
Console.WriteLine("Joining year of Employee is: {0}", this.join_year);
Console.WriteLine("Age of Employee is: {0}", this.age);
Console.WriteLine("Department of Employee is: {0}", this.dept);
}
}
static void Main(string[] args)
{
Employee emp = new Employee();
Console.Write("Enter Joining Year: ");
int join_year = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Age: ");
int age = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Department: ");
string dept = Console.ReadLine();
emp.getval(join_year, age, dept);
emp.showval();
}
}
}
So yeah basically over here I'm adding the values and they are getting printed too. Now I just want to take these records add it into a list or array so that I can access the records by choice.
if I understand it right, you want to do this.
List<string>() list = new List<string>();
for(int i = 0; i < 3; i++)
{
switch(i)
{
case 0: list.Add(join_year.ToString());
break;
case 1: list.Add(age.ToString());
break;
case 2: list.Add(dept);
break;
}
}
it is pretty simplistic, but will do the job.
class Program
{
struct St_test
{
public string f_name;
public string l_name;
public int age;
public string email;
}
static void proced(int number)
{
St_test s = new St_test();
Console.WriteLine("Enter the first name :");
s.f_name = Console.ReadLine();
Console.WriteLine("Enter the last name :");
s.l_name = Console.ReadLine();
agee:
Console.WriteLine("Enter the age :");
try { s.age = int.Parse(Console.ReadLine()); }
catch { Console.WriteLine("You enterd viod age"); goto agee; }
Console.WriteLine("Enter the e_mail :");
s.email = Console.ReadLine();
}
static void Main(string[] args)
{
int num;
nume:
Console.WriteLine("enter the count of people you would like to store");
try { num = int.Parse(Console.ReadLine()); }
catch { Console.WriteLine("you enterd void number"); goto nume; }
for (int i = 0; i < num; i++)
{
proced(num);
}
I want to input many of (S) to every number (num) of people.
How to repeat the procedure (proced) and every repeat the (s) variable has new name.
If I write in the procedure (proced) the next :
string r = "s" + number;
how to convert the resulted string (r) to variable to use it instead of (s) variable for each loop
You can't (easily, anyway) access variables by name like that - but there's a much better solution, which is to create a collection of some kind - an array or a list, for example.
I would suggest:
Changing your St_test struct:
Make it a non-nested type
Give it a clearer name (e.g. Person)
Make it a class
Don't expose fields - expose properties
Potentially make it immutable, taking all the values in the constructor
Changing your proced method:
Make it return a new Person
Change the name to follow .NET naming conventions
Stop using goto
Factor out the "request an integer from the user" into a method
Changing your Main method:
Create a List<Person>
Repeatedly call what used to be called proced. but add the return value into the list
You'll end up with code something like this - but don't blindly copy it. Make sure you understand everything that's happening here.
using System;
using System.Collections.Generic;
public sealed class Person
{
public string FirstName { get; }
public string LastName { get; }
public int Age { get; }
public string Email { get; }
public Person(string firstName, string lastName, int age, string email)
{
// TODO: Validation
FirstName = firstName;
LastName = lastName;
Age = age;
Email = email;
}
}
public class Test
{
private static Person CreatePersonFromUserInput()
{
Console.WriteLine("Enter the first name:");
string firstName = Console.ReadLine();
Console.WriteLine("Enter the last name:");
string lastName = Console.ReadLine();
Console.WriteLine("Enter the age:");
int age = RequestInt32();
Console.WriteLine("Enter the email address:");
string email = Console.ReadLine();
return new Person(firstName, lastName, age, email);
}
private static int RequestInt32()
{
string text = Console.ReadLine();
int ret;
while (!int.TryParse(text, out ret))
{
Console.WriteLine("Invalid value. Please try again.");
text = Console.ReadLine();
}
return ret;
}
private static void Main()
{
Console.WriteLine("Enter the count of people you would like to store:");
int count = RequestInt32();
List<Person> people = new List<Person>();
for (int i = 0; i < count; i++)
{
people.Add(CreatePersonFromUserInput());
}
// Just to show them...
foreach (Person person in people)
{
Console.WriteLine(
$"First: {person.FirstName}; Last: {person.LastName}; Age: {person.Age}; Email: {person.Email}");
}
}
}
I have been searching about creating a new object within a loop, found some answers and topics but its way too hard to understand. Making it with lists and arrays etc.
What I am trying to do is, get an input from the user(lets say 3), and create objects as many as the user will with the unique names. Like newperson1, newperson2, newperson3 etc.
My code looks like this:
class person
{
}
class Program
{
static void Main(string[] args)
{
Console.Write("How many persons you want to add?: ");
int p = int.Parse(Console.ReadLine());
for (int i = 0; i < p; i++)
{
person newperson = new person();
}
}
}
Is there any way to create new objects with following numbers in the end of the object name?
Thanks!
Edit:
My new code looks like this; I was more thinking like this:
class Persons
{
//Person object id
public int id { get; set; }
//Persons name
public string name { get; set; }
//Persons adress
public string adress { get; set; }
//Persons age
public int age { get; set; }
}
class Program
{
static void Main(string[] args)
{
Console.Write("How many persons you want to add?: ");
int count = int.Parse(Console.ReadLine());
var newPersons = new List<Persons>(count);
for (int i = 0; i < count; i++)
{
newPersons[i].id = i;
Console.Write("Write name for person " + i);
newPersons[i].name = Console.ReadLine();
Console.Write("Write age for person " + i);
newPersons[i].age = int.Parse(Console.ReadLine());
Console.Write("Write adress for person " + i );
newPersons[i].adress = Console.ReadLine();
}
Console.WriteLine("\nPersons \tName \tAge \tAdress");
for (int i = 0; i < count; i++)
{
Console.WriteLine("\t" + newPersons[i].name + "\t" + newPersons[i].age + "\t" + newPersons[i].adress);
}
Console.ReadKey();
}
}
I understand that I have to create object with arrays or lists. But I didn't really understand how I will access them after they are created person by person..
It's fairly advanced to create dynamic classes (where the actual name of the object is different). In other words, it's WAY harder to do what you're asking than to create a List or an Array. If you spend an hour or two studying Collections, it will pay off in the long run.
Also, you might consider adding a Name property to your Person class, and then you can set that differently for each person you create.
As others have said, you will need to store them in an array or list:
public class Person
{
public string Name { get; set; }
}
static void Main(string[] args)
{
Console.Write("How many persons you want to add?: ");
int p = int.Parse(Console.ReadLine());
var people = new List<Person>();
for (int i = 0; i < p; i++)
{
// Here you can give each person a custom name based on a number
people.Add(new Person { Name = "Person #" + (i + 1) });
}
}
Here's an example of one way to access a Person from the list and let the user update the information. Note that I've added a few properties to the Person class:
public class Person
{
public string Name { get; set; }
public DateTime DateOfBirth { get; set; }
public string Address { get; set; }
public int Age
{
// Calculate the person's age based on the current date and their birthday
get
{
int years = DateTime.Today.Year - DateOfBirth.Year;
// If they haven't had the birthday yet, subtract one
if (DateTime.Today.Month < DateOfBirth.Month ||
(DateTime.Today.Month == DateOfBirth.Month &&
DateTime.Today.Day < DateOfBirth.Day))
{
years--;
}
return years;
}
}
}
private static void GenericTester()
{
Console.Write("How many persons you want to add?: ");
string input = Console.ReadLine();
int numPeople = 0;
// Make sure the user enters an integer by using TryParse
while (!int.TryParse(input, out numPeople))
{
Console.Write("Invalid number. How many people do you want to add: ");
input = Console.ReadLine();
}
var people = new List<Person>();
for (int i = 0; i < numPeople; i++)
{
// Here you can give each person a custom name based on a number
people.Add(new Person { Name = "Person" + (i + 1) });
}
Console.WriteLine("Great! We've created {0} people. Their temporary names are:",
numPeople);
people.ForEach(person => Console.WriteLine(person.Name));
Console.WriteLine("Enter the name of the person you want to edit: ");
input = Console.ReadLine();
// Get the name of a person to edit from the user
while (!people.Any(person => person.Name.Equals(input,
StringComparison.OrdinalIgnoreCase)))
{
Console.Write("Sorry, that person doesn't exist. Please try again: ");
input = Console.ReadLine();
}
// Grab a reference to the person the user asked for
Person selectedPerson = people.First(person => person.Name.Equals(input,
StringComparison.OrdinalIgnoreCase));
// Ask for updated information:
Console.Write("Enter a new name (or press enter to keep the default): ");
input = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(input))
{
selectedPerson.Name = input;
}
Console.Write("Enter {0}'s birthday (or press enter to keep the default) " +
"(mm//dd//yy): ", selectedPerson.Name);
input = Console.ReadLine();
DateTime newBirthday = selectedPerson.DateOfBirth;
if (!string.IsNullOrWhiteSpace(input))
{
// Make sure they enter a valid date
while (!DateTime.TryParse(input, out newBirthday) &&
DateTime.Today.Subtract(newBirthday).TotalDays >= 0)
{
Console.Write("You must enter a valid, non-future date. Try again: ");
input = Console.ReadLine();
}
}
selectedPerson.DateOfBirth = newBirthday;
Console.Write("Enter {0}'s address (or press enter to keep the default): ",
selectedPerson.Name);
input = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(input))
{
selectedPerson.Address = input;
}
Console.WriteLine("Thank you! Here is the updated information:");
Console.WriteLine(" - Name ............ {0}", selectedPerson.Name);
Console.WriteLine(" - Address ......... {0}", selectedPerson.Address);
Console.WriteLine(" - Date of Birth ... {0}", selectedPerson.DateOfBirth);
Console.WriteLine(" - Age ............. {0}", selectedPerson.Age);
}
The closest thing to doing what you are asking is to create a dictionary:
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var dictionary = new Dictionary<string, Person>();
Console.Write("How many persons you want to add?: ");
int p = int.Parse(Console.ReadLine());
for (int i = 0; i < p; i++)
{
dictionary.Add("NewPerson" + i, new Person());
}
// You can access them like this:
dictionary["NewPerson1"].Name = "Tim Jones";
dictionary["NewPerson2"].Name = "Joe Smith";
}
public class Person
{
public string Name {
get;
set;
}
}
}
You can create dynamically named variables in C#.
What you need is a collection of persons:
var persons = new List<person>();
for (int i = 0; i < p; i++)
{
persons.Add(new person());
}
Arrays and List are basic building blocks. they should't be very hard. but if you don't want to deal with them try creating a method whose responsibility is to give you your new objects given count.
static void Main(string[] args)
{
Console.Write("How many persons you want to add?: ");
int p = int.Parse(Console.ReadLine());
var newPersons = CreatePersons(p);
foreach (var person in newPersons)
{
Console.WriteLine("Eneter age for Person :" person.Name);
person.Age = Console.ReadLine();
}
}
static IEnumerable<Person> CreatePersons(int count)
{
for (int i = 0; i < count; i++)
{
yield return new Person{ Name="newPerson" +1 };
}
}
Try this one.
I am creating Person (Object) as array first (like creating object array)
Then I am assigning that to the Person Class.
class Persons
{
//Person object id
public int id { get; set; }
//Persons name
public string name { get; set; }
//Persons adress
public string adress { get; set; }
//Persons age
public int age { get; set; }
}
class Program
{
static void Main(string[] args)
{
Console.Write("How many persons you want to add?: ");
int count = int.Parse(Console.ReadLine());
//var newPersons = new List<Persons>(count);
Persons[] newPersons = new Persons[count];
for (int i = 0; i < count; i++)
{
newPersons[i] = new Persons();
newPersons[i].id = i+1;
Console.Write("Write name for person " + (i+1) + "\t");
newPersons[i].name = Console.ReadLine();
Console.Write("Write age for person " + (i + 1) + "\t");
newPersons[i].age = int.Parse(Console.ReadLine());
Console.Write("Write adress for person " + (i + 1) + "\t");
newPersons[i].adress = Console.ReadLine();
}
Console.WriteLine("\nPersons Name \tAge \tAdresss \n");
for (int i = 0; i < count; i++)
{
Console.WriteLine(newPersons[i].name + "\t\t" + newPersons[i].age + "\t" + newPersons[i].adress);
}
Console.ReadKey();
}
}
If you want to iterate through an array of object in C#, you need to define the ToString() method (override) and after that, you can use the ToString() method.
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];