I am having a problem getting my program to check the input previous and compare it so the user cannot duplicate an order number. Right now the program will run all the way through and look the way I want, but it accepts duplicate order numbers while I would like it to inform the user and ask them to reenter. The problem seems to be that my check[y] array does not contain any value when I compare it. How do I get this array to contain the previously entered order numbers so it will display the error message. I am just going to post the entire code so you can see what I have done so far. Others have suggested the List type, but I am a student and have not learned this yet. I believe I am supposed to use the Equals method. Any help would be appreciated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Assignment6_Hergott
{
class Order : IComparable <Order>
{
public int orderNumber { get; set; }
public string customerName { get; set; }
public int quanityOrdered { get; set; }
public double total;
public const double priceEach = 19.95;
public Order()
{
}
public Order(int number, string name, int quanity)
{
number = orderNumber;
name = customerName;
quanity = quanityOrdered;
}
public double totalPrice
{
get
{
return total;
}
}
public int CompareTo(Order o)
{
return this.orderNumber.CompareTo(o.orderNumber);
}
public override bool Equals(Object e)
{
bool equal;
Order temp = (Order)e;
if (orderNumber == temp.orderNumber)
equal = true;
else
equal = false;
return equal;
}
public override int GetHashCode()
{
return Convert.ToInt32(orderNumber);
}
public override string ToString()
{
return "ShippedOrder " + orderNumber + " " + customerName + " " + quanityOrdered +
" # " + priceEach + " each.";
}
}
class ShippedOrder : Order
{
public const int shippingFee = 4;
public override string ToString()
{
return base.ToString() + " Shipping is " + shippingFee + " Total is " + totalPrice;
}
}
class Program
{
static void Main(string[] args)
{
double sum = 0;
ShippedOrder[] orderArray = new ShippedOrder[5];
ShippedOrder[] check = new ShippedOrder[5];
bool wrong = true;
for (int x = 0; x < orderArray.Length; ++x)
{
orderArray[x] = new ShippedOrder();
Console.Write("Enter order number: ");
orderArray[x].orderNumber = Convert.ToInt32(Console.ReadLine());
for (int y = 0; y < x; y++)
{
check[y] = new ShippedOrder();
if (orderArray[x].Equals(check[y]))
wrong = false;
while (!wrong)
{
Console.WriteLine("Sorry, the order number {0} is a duplicate.
\nPlease reenter: ", orderArray[x].orderNumber);
for (y = 0; y < x; y++)
{
if (orderArray[x].Equals(check[y]))
wrong = false;
}
check[y] = orderArray[x];
}
}
Console.Write("Enter cusomer name: ");
orderArray[x].customerName = Console.ReadLine();
Console.Write("Enter quanity: ");
orderArray[x].quanityOrdered = Convert.ToInt32(Console.ReadLine());
orderArray[x].total = orderArray[x].quanityOrdered * Order.priceEach +
ShippedOrder.shippingFee;
sum += orderArray[x].total;
}
Array.Sort(orderArray);
for (int x = 0; x < orderArray.Length; x++)
{
Console.WriteLine(orderArray[x].ToString());
}
Console.WriteLine();
Console.WriteLine("Total for all orders is {0:c} ", sum);
}
}
}
I had a few minutes so I changed my answer to show you one way it could be done. If you just copy/paste this you'll be doing yourself a disservice, though (and your instructor will probably be able to tell). Take a look at the solution and see how it differs from yours. I hesitated to post a full solution but I thought this might be an okay way for you to figure out what you'd done wrong.
namespace ConsoleApplication2
{
using System;
using System.Linq;
public class Order : IComparable<Order>
{
public const double PriceEach = 19.95;
public Order()
{
}
public Order(int number, string name, int quanity)
{
this.OrderNumber = number;
this.CustomerName = name;
this.QuanityOrdered = quanity;
}
public int OrderNumber { get; set; }
public string CustomerName { get; set; }
public int QuanityOrdered { get; set; }
public int CompareTo(Order o)
{
return this.OrderNumber.CompareTo(o.OrderNumber);
}
public override bool Equals(object e)
{
int compareTo;
int.TryParse(e.ToString(), out compareTo);
return this.OrderNumber == compareTo;
}
public override int GetHashCode()
{
return Convert.ToInt32(this.OrderNumber);
}
public override string ToString()
{
return "Shipped order number " + this.OrderNumber + " for customer " + this.CustomerName + " " + this.QuanityOrdered +
" # $" + PriceEach + " each.";
}
}
public class ShippedOrder : Order
{
public const int ShippingFee = 4;
public double TotalPrice
{
get
{
return (this.QuanityOrdered * PriceEach) + ShippingFee;
}
}
public override string ToString()
{
return base.ToString() + " Shipping is $" + ShippingFee + ". Total is $" + this.TotalPrice;
}
}
public class Program
{
private static readonly int[] OrderNumbers = new int[5];
private static readonly ShippedOrder[] ShippedOrders = new ShippedOrder[5];
public static void Main(string[] args)
{
double sum = 0;
for (var i = 0; i < OrderNumbers.Length; i++)
{
OrderNumbers[i] = InputOrderNumber();
var name = InputCustomerName();
var quantity = InputQuantity();
ShippedOrders[i] = new ShippedOrder { CustomerName = name, QuanityOrdered = quantity, OrderNumber = OrderNumbers[i] };
sum += ShippedOrders[i].TotalPrice;
}
Array.Sort(ShippedOrders);
foreach (var t in ShippedOrders)
{
Console.WriteLine(t.ToString());
}
Console.WriteLine();
Console.WriteLine("Total for all orders is {0:c} ", sum);
Console.WriteLine();
Console.WriteLine("Press enter to exit.");
Console.ReadLine();
}
private static int InputOrderNumber()
{
Console.Write("Enter order number: ");
var parsedOrderNumber = InputNumber();
if (ShippedOrders.Any(shippedOrder => shippedOrder != null && shippedOrder.OrderNumber.Equals(parsedOrderNumber)))
{
Console.WriteLine("Order number {0} is a duplicate.", parsedOrderNumber);
return InputOrderNumber();
}
return parsedOrderNumber;
}
private static string InputCustomerName()
{
Console.Write("Enter customer name: ");
var customerName = Console.ReadLine();
if (customerName == null || string.IsNullOrEmpty(customerName.Trim()))
{
Console.WriteLine("Customer name may not be blank.");
return InputCustomerName();
}
return customerName;
}
private static int InputQuantity()
{
Console.Write("Enter quantity: ");
return InputNumber();
}
private static int InputNumber()
{
int parsedInput;
var input = Console.ReadLine();
if (!int.TryParse(input, out parsedInput))
{
Console.WriteLine("Enter a valid number.");
return InputNumber();
}
return parsedInput;
}
}
}
my check[y] array does not contain any value when I compare it. How do
I get this array to contain the previously entered order numbers
If you want check[] to contain order numbers, it needs to be of the type of order number (an int, in this case). So whenever you add a new order to the orderArray, also add its number to the check array. Then you can test against earlier numbers.
If this doesn't solve your problem, add a follow-up question as a comment telling us what you tried and we can go from there.
Related
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed last year.
I have found nothing to answer this question, and I think it is different for my code. Probably because I am adding a custom object to an array, but I still don't know what is causing this. The error is on line 35. Code attached below.
using System;
class Player {
public string abilitySet;
public string name;
public void useAbility() {
if (abilitySet == "fire") {
Console.WriteLine(name + " used fireball which did 40 damage!");
}
}
}
class Match {
public int PlayerCount;
public Player[] players;
public void Start() {
Console.WriteLine("Game started! There are " + PlayerCount + " players!");
}
}
class Program {
public static void Main(string[] args) {
Match match = new Match();
Console.WriteLine("How many players are there?");
string playerCount = Console.ReadLine();
if (Int32.TryParse(playerCount, out int j)) {
Console.WriteLine("You have selected " + playerCount + " players!");
match.PlayerCount = j;
for (int i = 0; i < j; i++) {
Player plr = new Player();
match.players[i] = plr;
plr.name = "Player " + i;
Console.WriteLine("What do you want " + plr.name + "'s ability set to be?");
string ability = Console.ReadLine();
if (ability.ToLower() == "fire") {
Console.WriteLine(plr.name + " has " + ability + "!");
} else {
Console.WriteLine("That is not a ability!");
}
}
} else {
Console.WriteLine("Please enter a number of players not text!");
}
}
}
As #Backs mentioned, you are not initializing your variables. But I would organize your code as follows and use a List instead of an array. Much easier to read don't you think?
using System;
class Player
{
public Player(string name)
{
Name = name;
}
public string Name { get; set; } = String.Empty;
public string AbilitySet { get; set; } = String.Empty;
public void UseAbility()
{
if (AbilitySet == "fire")
{
Console.WriteLine(Name + " used fireball which did 40 damage!");
}
}
}
class Match
{
public List<Player> Players { get; set; } = new List<Player>();
public void Start()
{
Console.WriteLine("Game started! There are " + Players.Count + " players!");
}
}
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("How many players are there? Or type Q+ENTER to quit.");
int numberOfPlayers = 0;
while (true)
{
string input = Console.ReadLine();
if (input == "Q")
{
System.Environment.Exit(1);
}
if (!Int32.TryParse(input, out numberOfPlayers))
{
Console.WriteLine("Invalid input. Please enter a numeric value.");
continue;
}
if (numberOfPlayers <= 0)
{
Console.WriteLine("Number of players must be at least 1.");
continue;
}
break;
}
Match match = new Match();
for (int i = 0; i < numberOfPlayers; i++)
{
match.Players.Add(new Player($"Player {i + 1}"));
}
match.Start();
}
}
Field players of Match class is not initialized. You should create an array:
match.players = new Player[j];
Or do it in constructor:
class Match {
public int PlayerCount;
public Player[] players;
public Match(int count) {
PlayerCount = count;
players = new Player[count];
}
public void Start() {
Console.WriteLine("Game started! There are " + PlayerCount + " players!");
}
}
Match match = new Match(j);
Doing a school activity but I hit a roadblock. I can't seem to make the program output the arrays I've entered. The output works when the variables inside the PlayerCharacter() and Mage() were all regular variables. Then I turned them into arrays because that was what was required of us, but then it started not showing anything during output.
using System;
namespace Summative
{
class PlayerCharacter
{
string[] name = new string[10];
int[] life = new int[10];
char[] gender = new char[10];
public int i = 0;
public int x = 0;
public PlayerCharacter()
{
Console.Write("Enter character name: ");
this.Name = Console.ReadLine();
Console.Write("Enter Life: ");
this.Life = int.Parse(Console.ReadLine());
Console.Write("Enter Gender (M/F): ");
this.Gender = char.Parse(Console.ReadLine());
i++;
}
public string Name
{
get
{
return name[i];
}
set
{
name[i] = value;
}
}
public int Life
{
get
{
return life[i];
}
set
{
life[i] = value;
}
}
public char Gender
{
get
{
return gender[i];
}
set
{
if (value == 'M' || value == 'F')
{
gender[i] = value;
}
else
{
Console.WriteLine("Invalid Gender!");
}
}
}
public virtual void Output()
{
Console.WriteLine("Name: " + string.Join(",", Name));
Console.WriteLine("Life: " + string.Join(",", Life));
Console.WriteLine("Gender: " + string.Join(",", Gender));
}
}
class Mage : PlayerCharacter
{
string[] element = new string[10];
int[] mana = new int[10];
public Mage() : base()
{
Console.Write("Enter element: ");
this.Elements = Console.ReadLine();
Console.Write("Enter mana: ");
this.Mana = int.Parse(Console.ReadLine());
}
public string Elements
{
get
{
return element[x];
}
set
{
element[x] = value;
}
}
public int Mana
{
get
{
return mana[x];
}
set
{
mana[x] = value;
}
}
public override void Output()
{
base.Output();
Console.WriteLine("Element: " + string.Join(",", Elements));
Console.WriteLine("Mana: " + string.Join(",", Mana));
x++;
}
}
class Rogue : PlayerCharacter
{
string faction;
float energy;
public Rogue() : base()
{
Console.Write("Enter faction name: ");
this.Faction = Console.ReadLine();
Console.Write("Enter energy: ");
this.Energy = float.Parse(Console.ReadLine());
}
public string Faction
{
get
{
return faction;
}
set
{
faction = value;
}
}
public float Energy
{
get
{
return energy;
}
set
{
energy = value;
}
}
public override void Output()
{
base.Output();
Console.WriteLine("Faction: " + Faction);
Console.WriteLine("Energy: " + Energy);
}
}
class Fighter : PlayerCharacter
{
string weapon;
double strength;
public Fighter() : base()
{
Console.Write("Enter weapon name: ");
this.Weapon = Console.ReadLine();
Console.Write("Enter strength: ");
this.Strength = double.Parse(Console.ReadLine());
}
public string Weapon
{
get
{
return weapon;
}
set
{
weapon = value;
}
}
public double Strength
{
get
{
return strength;
}
set
{
strength = value;
}
}
public override void Output()
{
base.Output();
Console.WriteLine("Weapon: " + Weapon);
Console.WriteLine("Strength: " + Strength);
}
}
class TestPlayer
{
static void Main(string[] args)
{
PlayerCharacter character;
CharacterCreator:
int switchchoice = 0;
Console.WriteLine("Select a class");
Console.WriteLine("1. Mage");
Console.WriteLine("2. Rogue");
Console.WriteLine("3. Fighter");
Console.WriteLine("0. Exit");
Console.Write("Enter Choice: ");
start:
try
{
switchchoice = int.Parse(Console.ReadLine());
}
catch
{
Console.Clear();
Console.WriteLine("Invalid Input! Please Try Again.");
goto CharacterCreator;
}
switch (switchchoice)
{
case 1:
Console.Clear();
character = new Mage();
character.Output();
break;
case 2:
Console.Clear();
character = new Rogue();
character.Output();
break;
case 3:
Console.Clear();
character = new Fighter();
character.Output();
break;
case 0:
Console.Clear();
goto start;
default:
Console.Clear();
Console.WriteLine("Invalid Input! Please Try Again.");
goto CharacterCreator;
}
int choice;
int y = 0;
int z;
int i = character.i;
int x = character.x;
Console.Clear();
Console.WriteLine("Player Character Designer");
Console.WriteLine("1. Create");
Console.WriteLine("2. View");
Console.Write("Enter Choice: ");
choice = int.Parse(Console.ReadLine());
if (choice == 1)
{
goto CharacterCreator;
}
else if (choice == 2)
{
z = i;
i = 0;
x = 0;
do
{
character.Output();
Console.WriteLine(" ");
y++;
i++;
x++;
} while (y != z);
}
}
}
}
Answer: Use a list
The main issue is that you should add the created characters in a list rather than keeping arrays of attributes inside characters. This lets you loop over each character and print all the information in turn. I.e.
var myCharacters = new List<PlayerCharacter>();
...
myCharacters.Add(myCharacter);
Other Issues
Constructors & object design
Inject parameters in constructors whenever possible, and use auto-properties when applicable. This helps avoid complex logic in the constructors, and reduces the size of the classes. Let the creator of the characters be responsible for reading the necessary parameters. I would also prefer to separate the construction of the information-string and the output, that way you can output the same information to a log file or whatever, and not just to the console. I.e:
class PlayerCharacter
{
public string Name { get; }
public int Life { get; }
public string Gender { get; }
public PlayerCharacter(string name, int life, string gender)
{
Name = name;
Life = life;
Gender = gender;
}
public override string ToString()
{
return $"Name: {Name}, Life {Life}, Gender: {Gender}";
}
}
Control flow
Use loops instead of goto. While I think there are cases where goto is the best solution, they are rare, and the general recommendation is to use loops for control flow i.e. something like this pseudocode
MyOptions option;
var myCharacters = new List<PlayerCharacter>();
do{
myCharacters.Add(ReadCharacter());
option = ReadOption();
}
while(option != MyOptions.ViewCharacters);
PrintCharacters(myCharacters);
Split code into methods
Move code into logical functions, especially for repeated code. This helps to make it easier to get a overview of the program. For example, for reading numbers it is better to use the TryParse function than trying to catch exceptions, and put it in a method to allow it to be reused:
int ReadInteger()
{
int value;
while (!int.TryParse(Console.ReadLine(), out value))
{
Console.WriteLine("Invalid Input! Please Try Again.");
}
return value;
}
This is homework, but a small portion...
I'm trying to return the largest number in an array using arr.MAX(); , but I keep on getting zero.
After debugging, I can see that values are being stored (from the user) yet it still returns zero.
The method in question is at the bottom.
Class ElectionUI
{
public void candidateInfo()
{
do
{
for (int i = 0; i < theElection.CandidateNames.Length; i++)
{
Console.Write("Please enter the name for Candidate #" + (i +
1) + ": ");
theElection.CandidateNames[i] = Console.ReadLine();
Console.Write("Please enter the number of votes for: {0}: ",
theElection.CandidateNames[i]);
theElection.NumVotes[i] = int.Parse(Console.ReadLine());
Console.WriteLine("");
}
} while (theElection.NumVotes.Length < 5);
}
}
Class Election
{
private string[] candidateNames = new string[5];
private int[] numVotes = new int[5];
//get/set Candidate Names
public string[] CandidateNames
{
get { return candidateNames; }
set { candidateNames = value; }
}
//Get/Set Candidate votes
public int[] NumVotes
{
get { return numVotes; }
set { numVotes = value; }
}
public void findWinner()
{
int max = NumVotes.Max();
for (var i = 0; i < numVotes.Length; i++)
{
if (NumVotes[i] > max)
{
max = NumVotes[i];
}
}
Console.WriteLine(max);
}
}
from the code its not clear, how you are initializing you election class instance, and how you are calling findWinner method. And yes your Do-While looping doing nothing. Because you already set the name array length as 5 so it will run the for loop once and then it will exit. even if you remove your do-while you will get the same output.
check the fiddle your code is working fine. I just assume you are creating instance of Election and then passing it to ElectionUI class to use it.
https://dotnetfiddle.net/oiVK9g
using System;
using System.Linq;
public class Program
{
public static void Main()
{
var ele = new Election();
var ui = new ElectionUI(ele);
ui.candidateInfo();
ele.findWinner();
}
}
class ElectionUI
{
Election theElection;
public ElectionUI(Election obj)
{
theElection = obj;
}
public void candidateInfo()
{
do
{
for (int i = 0; i < theElection.CandidateNames.Length; i++)
{
Console.Write("Please enter the name for Candidate #" + (i +
1) + ": ");
theElection.CandidateNames[i] = Console.ReadLine();
Console.Write("Please enter the number of votes for: {0}: ",
theElection.CandidateNames[i]);
theElection.NumVotes[i] = int.Parse(Console.ReadLine());
Console.WriteLine("");
}
} while (theElection.NumVotes.Length < 5);
}
}
class Election
{
private string[] candidateNames = new string[5];
private int[] numVotes = new int[5];
//get/set Candidate Names
public string[] CandidateNames
{
get { return candidateNames; }
set { candidateNames = value; }
}
//Get/Set Candidate votes
public int[] NumVotes
{
get { return numVotes; }
set { numVotes = value; }
}
public void findWinner()
{
int max = NumVotes.Max();
Console.WriteLine(max);
}
}
I think that you wanted to return the candidate name of who won, right?
Using your code you should change the findWinner method to:
public void findWinner()
{
int max = NumVotes.Max();
string winnerName = null;
for (var i = 0; i < numVotes.Length; i++) {
if (NumVotes[i] = max) {
winnerName = CandidateNames[i];
}
}
Console.WriteLine(winnerName);
}
You need to initialize the local variable max with Int32.MinValue. That way any value encountered will replace it.
namespace Theprogram.cs
{
class Program
{
static void Main(string[] args)
{
CreditCustomer[] creditCustomer = new CreditCustomer[5];
int x, y;
bool goodNum;
for (x = 0; x < creditCustomer.Length; ++x)
{
creditCustomer[x] = new CreditCustomer();
Console.Write("Enter customer number ");
creditCustomer[x].CustomerNumber = Convert.ToInt32(Console.ReadLine());
goodNum = true;
for (y = 0; y < x; ++y)
{
if (creditCustomer[x].Equals(creditCustomer[y]))
goodNum = false;
}
while (!goodNum)
{
Console.Write("Sorry, the customer number " +
creditCustomer[x].CustomerNumber + " is a duplicate. " +
"\nPlease reenter ");
creditCustomer[x].CustomerNumber = Convert.ToInt32(Console.ReadLine());
goodNum = true;
for (y = 0; y < x; ++y)
{
if (creditCustomer[x].Equals(creditCustomer[y]))
goodNum = false;
}
}
Console.Write("Enter name ");
creditCustomer[x].CustomerName = Console.ReadLine();
Console.Write("Enter age ");
creditCustomer[x].Rate = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter amount due ");
creditCustomer[x].AmountDue = Convert.ToDouble(Console.ReadLine());
}
Array.Sort(creditCustomer);
Array.Sort(customer);
}
}
class Customer : IComparable<Customer>
{
private int customerNumber;
public int CustomerNumber
{
get
{
return customerNumber;
}
set
{
customerNumber = value;
}
}
private string customerName;
public string CustomerName
{
get
{
return customerName;
}
set
{
customerName = value;
}
}
private double amountDue;
public double AmountDue
{
get
{
return amountDue;
}
set
{
amountDue = value;
}
}
public Customer(int num, string name, int amt)
{
CustomerNumber = num;
CustomerName = name;
AmountDue = amt;
}
public Customer(): this(9, "ZZZ", 0)
{
}
public override bool Equals(Object e)
{
bool equal;
Customer temp = (Customer)e;
if (this.CustomerNumber == temp.CustomerNumber)
equal = true;
else
equal = false;
return equal;
}
public override int GetHashCode()
{
return CustomerNumber;
}
public override string ToString()
{
return (GetType() + " Credit Customer " + CustomerNumber + " " + CustomerName +
" Amount Due is " + AmountDue.ToString("C") + " Interest rate is ");
}
protected virtual int IComparable.CompareTo(Object o)
{
int returnVal;
Customer temp = (Customer)o;
if (this.CustomerNumber >
temp.CustomerNumber)
returnVal = 1;
else
if (this.CustomerNumber < temp.CustomerNumber)
returnVal = -1;
else
returnVal = 0;
return returnVal;
}
}
class CreditCustomer : Customer, IComparable<CreditCustomer>
{
public int Rate {get; set;}
int MonthlyPayment { get; set; }
public CreditCustomer(int customerNumber, string customerName, int amountDue, int Rate) : base(customerNumber, customerName, amountDue)
{ }
public CreditCustomer(): this(0, "", 0, 0)
{ }
public override string ToString()
{
return (GetType() + " Credit Customer " + CustomerNumber + " " + CustomerName +
" Amount Due is " + AmountDue.ToString("C") + " Interest rate is " + Rate + " Monthly Payment is " + MonthlyPayment);
}
int IComparable.CompareTo(object o)
{
int returnVal;
CreditCustomer temp = (CreditCustomer)o;
if (this.CustomerNumber > temp.CustomerNumber)
returnVal = 1;
else
if (this.CustomerNumber < temp.CustomerNumber)
returnVal = -1;
else
returnVal = 0;
return returnVal;
}
}
}
I am having trouble implementing Icomparable in C# for my parent and child classes as I get the error:
does not implement interface member'System.IComparable.CompareTo
I really need help on how to implement the Icomparable interface so that I can use the compareTo method on my array of object. Any help would be greatly appreciated.
If you're using Visual Studio and are not sure how to implement an interface, just right click IComparable in the class declaration
class CreditCustomer : Customer, IComparable<CreditCustomer>
and select Implement Interface and any of the two options.
The correct signature for the implementation in CreditCustomer would be either:
public int CompareTo(CreditCustomer other)
{
}
or
int IComparable<CreditCustomer>.CompareTo(CreditCustomer other)
{
}
Note that the second signature would hide the method unless you cast the object to IComparable<CreditCustomer>.
As SLaks mentioned in his comment, there are, in fact, two different interfaces that are named IComparable which can be easily confused:
IComparable is an older, non-generic interface which allows comparison between an object and any other object. There's no type checking - your CreditCustomer can be compared to an int or a List<string> or anything. This interface defines a single method, CompareTo(object obj). This is the method you have in your class.
IComparable<T> is a newer, generic interface. It's very similar to IComparable, but enforces type checking - it only compares T to T, so you don't have to write a lot of boilerplate code making sure that someone didn't try to compare your CreditCustomer to a Dog or something. It also defines a single method - CompareTo(T obj). This is the interface that you marked your class as implementing.
Despite being similarly named, these two are, as far as the compiler is concerned, two different interfaces. If you don't have a CompareTo method that accepts a CreditCustomer argument, you're not implementing IComparable<CreditCustomer>, and that's why it's giving you an error. Either change your method signature to match the interface, or change the interface you're using to one that matches the method signature. Probably the former.
Learning C# on my own (not homework). I wrote a TotalDue method to calculate grand total of all customer balances due (from array). Placed it within the Customer class so it would have access to the data. I cannot figure out how to call this method in main. How do I get the total to display?
class Program
{
static void Main(string[] args)
{
Customer[] customers = new Customer[2];
string customer;
int id;
double due;
// GET DATA AND FILL ARRAY
for (int x = 0; x < customers.Length; ++x)
{
GetData(out customer, out id, out due);
customers[x] = new Customer(customer, id, due);
}
// SORT ARRAY - NEEDS ICOMPARABLE<Customer> - PART 1
Array.Sort(customers);
// PRINT ARRAY WITH TOSTRING() OVERRIDE
for (int x = 0; x < customers.Length; ++x)
{
Console.WriteLine(customers[x].ToString());
}
//DON'T KNOW HOW TO CALL THE TOTAL DUE METHOD...
Console.ReadLine();
}
class Customer : IComparable<Customer> // SORT ARRAY - PART 2
{
private string CustomerName { get; set; }
private int IdNumber { get; set; }
private double BalanceDue { get; set; }
// CONSTRUCTOR
public Customer(string customer, int id, double due)
{
CustomerName = customer;
IdNumber = id;
BalanceDue = due;
}
//SORT THE ARRAY - PART 3
public int CompareTo(Customer x)
{
return this.IdNumber.CompareTo(x.IdNumber);
}
// OVERRIDE TOSTRING TO INCLUDE ALL INFO + TOTAL
public override string ToString()
{
return ("\nCustomer: " + CustomerName + "\nID Number: " + IdNumber + "\nBalance Due: " + BalanceDue.ToString("C2"));
}
// TOTAL DUE FOR ALL CUSTOMERS
static void TotalDue(Customer [] customers)
{
double Total = 0;
for (int x = 0; x < customers.Length; ++x)
Total += customers[x].BalanceDue;
Console.WriteLine("Total Amount Due: {0}", Total.ToString("C2"));
}
}
// GET DATA METHOD
static void GetData(out string customer, out int id, out double due)
{
Console.Write("Please enter Customer Name: ");
customer = Console.ReadLine();
Console.Write("Please enter ID Number: ");
int.TryParse(Console.ReadLine(), out id);
Console.Write("Please enter Balance Due: $");
double.TryParse(Console.ReadLine(), out due);
}
}
Make TotalDue method public as the default access modifier in C# is private and then try this.
class Customer : IComparable<Customer> // SORT ARRAY - PART 2
{
public static void TotalDue(Customer [] customers)
{
double Total = 0;
for (int x = 0; x < customers.Length; ++x)
Total += customers[x].BalanceDue;
Console.WriteLine("Total Amount Due: {0}", Total.ToString("C2"));
}
}
static void Main(string[] args)
{
// ...........
//............
Customer.TotalDue(customers);
}
The default access modifier in C# is private. Since your TotalDue method does not specify anything else, it is private. You can change this to public and call it from your Main.
Add public access modifier with your static method and call it with name of class or remove the static keyword and make it instance and call class method.
make your Customer class method (TotalDue) Public and NOT static...