Array not returning max value - c#

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.

Related

Addresses of values in an array aren't static C#

So, I am currently making a little code with some pointers. I am trying to get every values of an array, and their respective address. However, the initial array is empty, and the user has to enter numbers as an input, which ends up being added to the array itself. Then, I want to get the address of each value that the user added, one by one. Everything works fine, except one thing; I want every value to have a static address. However, I noticed that at every inputs, every values had a different address than the one they had before. I tried to put the array as a global static variable, but it still doesn't work. Any help?
Thanks for everyone who takes their time to answer! <3
Full code:
using System;
public class ClearIt
{
public int k = 8;
}
public static class Arr
{
public static int StaticAddress;
public static int[] x = { };
}
public class Class
{
public static unsafe void Main()
{
ClearIt clearIt = new ClearIt();
int k2 = clearIt.k;
for (int j = 0; j < 1;)
{
string Read = Console.ReadLine();
int ReadToInt;
bool isTrue;
isTrue = int.TryParse(Read, out ReadToInt);
if (!isTrue)
{
return;
}
int StaticAdd = Arr.StaticAddress = ReadToInt;
if (k2 > 0)
{
var xList = Arr.x.ToList();
xList.Add(StaticAdd);
Arr.x = xList.ToArray();
Array.Sort(Arr.x);
k2--;
}
else if(k2 == 0)
{
Console.ForegroundColor = ConsoleColor.Red;
var xList2 = Arr.x.ToList();
xList2.Clear();
Arr.x = xList2.ToArray();
Console.WriteLine("Array cleared.");
Console.ForegroundColor = ConsoleColor.White;
k2 = 8;
}
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("\nValues\tAddresses");
for (int i = 0; i < Arr.x.Length; i++)
{
fixed (int* y = &Arr.x[i])
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("\n" + *y + $"\t{(long)y:X}\n");
Console.ForegroundColor = ConsoleColor.White;
}
}
}
}
}
The short answer is that everytime you assign to Arr.x you are creating a new array and a new part of memory is used.
The statement below for example causes Arr.x address to change
Arr.x = xList2.ToArray();
If you do not want to change the address of Arr.x, then only assign it once to the maximum length, and keep track of the item count actually stored.
My best guess is that you are trying to do something like this
where the addresses in memory do not change when items are added or the
array is cleared. After the 8th number is added, the list clears
and more numbers can be added
As you can see the address value does not change.
I am using fixed buffer arrays to store the values, instead of the regular array. Here is the code that generates the output above
class Program
{
static void Main(string[] args)
{
var arr = new FixedArray();
do
{
Console.Clear();
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine($"{"offset"}\t{"address"}\t{"value"}");
for (int i = 0; i < arr.Count; i++)
{
Console.ForegroundColor = ConsoleColor.Gray;
Console.Write($"{i}");
Console.ForegroundColor = ConsoleColor.Yellow;
Console.Write($"\t{arr.GetItemAddress(i)}");
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine($"\t{arr[i]:X}");
Console.ForegroundColor = ConsoleColor.Gray;
}
if (arr.Count == 0)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Array Cleared.");
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine();
}
Console.WriteLine("Enter Value:");
string input = Console.ReadLine();
if (int.TryParse(input, out int value))
{
if (arr.Add(value))
{
}
else
{
arr.Clear();
}
}
else
{
return;
}
} while (true);
}
}
and FixedArray is the object that actually stores the data
public unsafe struct FixedArray
{
public const int Size = 8;
fixed int data[Size];
public FixedArray(params int[] array) : this()
{
Count = Math.Min(Size, array.Length);
fixed (int* ptr = data)
{
for (int i = 0; i < Count; i++)
{
ptr[i] = array[i];
}
}
}
public IntPtr GetItemAddress(int offset = 0)
{
fixed (int* ptr = &data[offset])
{
return (IntPtr)ptr;
}
}
public int this[int offset]
{
get
{
if (offset >= 0 && offset < Count)
{
return data[offset];
}
return 0;
}
}
public int Count { get; private set; }
public void Clear() { Count = 0; }
public bool Add(int x)
{
if (Count < Size)
{
data[Count] = x;
Count++;
return true;
}
return false;
}
public int[] ToArray()
{
int[] array = new int[Count];
fixed (int* ptr = data)
{
for (int i = 0; i < Count; i++)
{
array[i] = ptr[i];
}
}
return array;
}
}
You don't have to use a fixed buffer array. You can just use a standard array, but with the readonly keyword so it only gets assigned once. Use the class below as a replacement to FixedArray above.
public class StdArray
{
public const int Size = 8;
public int Count { get; private set; }
readonly int[] data;
public StdArray(params int[] array)
{
data = new int[Size];
Count = Math.Min(Size, array.Length);
Array.Copy(array, data, Count);
}
public unsafe IntPtr GetItemAddress(int offset = 0)
{
fixed (int* ptr = &data[offset])
{
return (IntPtr)ptr;
}
}
public int this[int offset]
{
get
{
if (offset >= 0 && offset < Count)
{
return data[offset];
}
return 0;
}
}
public void Clear() { Count = 0; }
public bool Add(int x)
{
if (Count < Size)
{
data[Count] = x;
Count++;
return true;
}
return false;
}
public int[] ToArray()
{
int[] array = new int[Count];
Array.Copy(data, array, Count);
return array;
}
}

Array won't output anything

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;
}

adding objects in a list, am i doing it right?

namespace ConsoleApplication13
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("how many footballs would you want?");
int amount = int.Parse(Console.ReadLine());
List<football> ballist = new List<football>();
for (int i = 0; i < amount; i++)
{
Console.WriteLine("how much should football {0} weigh?", i+1);
int weight = int.Parse(Console.ReadLine());
ballist.Add(new football(weight));
}
Console.WriteLine("amount of footballs is {0}", amount);
ballist.ForEach(s => Console.WriteLine(s.GetWeight()));
Console.ReadLine();
}
}
class football
{
private int weight = 0;
public int GetWeight()
{
return weight;
}
public football(int weigh)
{
weight = weigh;
}
}
}
adding objects in a list, am i doing it right?
A possible alternative is to let user input all the weights in one go and generate the list:
Console.WriteLine("please, input footballs' weights separated by comma");
String input = Console.ReadLine();
List<football> ballist = input
.Split(',')
.Select(item => new football(int.Parse(item)))
.ToList();
Some suggestions on Football class
// We usually start classes with capital letter
class Football {
private int m_Weight;
// C# is not Java, so use properties, which are more readable
public int Weight {
get {
return m_Weight;
}
private set {
// validate input
if (value <= 0)
throw new ArgumentOutOfRangeException("value");
m_Weight = value;
}
}
// "weight" - let argument correspond to property
public football(int weight) {
Weight = weight;
}
}
The adding to the list is right. I would recomend you to use property for the Weight.
class football
{
public int weight { get; set; }
}
If you dont want to have any code on the get/set.
public int _weight;
public int weight
{
get
{
//Your Code here
return _weight;
}
set
{
//And Here
_weight = value;
}
}

Refer variable from different class

using System;
namespace Matrix_Algebra
{
public struct S_Matrix_size
{
public int size_R, size_C;
public S_Matrix_size(int r, int c)
{
this.size_R = r;
this.size_C = c;
}
}
public class C_Matrix_entries
{
public C_Matrix_entries()
{
int r, c;
Console.WriteLine("Enter number of rows and columns ");
r = Convert.ToInt32(Console.ReadLine());
c = Convert.ToInt32(Console.ReadLine());
S_Matrix_size size = new S_Matrix_size(r,c);
double[,] entry = new double [size.size_R,size.size_C];
Console.WriteLine("Enter the entries from first row [left to right] to the last row ");
for (int i = 0; i<size.size_R; i++)
{
Console.WriteLine("Enter the {0} row", i + 1);
for (int j = 0; j<size.size_C;j++)
{
entry[i, j] = Convert.ToDouble(Console.ReadLine());
}
}
}
}
}
namespace Row_Reduce_Algebra
{
using Matrix_Algebra;
public class TEST
{
static void Main()
{
C_Matrix_entries matrix_no1 = new C_Matrix_entries();
for (int i = 0; i < **matrix_no1.size**; i++)
{
}
}
}
}
As the title says, I'm trying to access a variable from a class instance, but don't know how to do it properly.
You can't access matrix_no1.size because size is inaccessible.
Add a public property to your C_Matrix_entries class, and reference it in Main().
public class C_Matrix_entries
{
public S_Matrix_size size { get; private set; }
public C_Matrix_entries()
{
...
size = new S_Matrix_size(r,c);
As #GrantWinney rightfully pointed out (as I was shaping up a working reply for you), you cannot access matrix_no1.size because it is inaccessible. (It is also out of scope being that matrix_no1 is a local variable declared in the default C_Matrix_entries constructor.)
Based on your code, here is an end-to-end working example of how to fix the problem using a somewhat different public property added to C_Matrix_entries. Beyond the flavor of the new S_Matrix_size public property you add to C_Matrix_entries (i.e. Grant Winney's will work too), you will need to compute the product of its size_R and size_C properties in your loop's setup.
using System;
namespace Matrix_Algebra
{
public struct S_Matrix_size
{
public int size_R, size_C;
public S_Matrix_size(int r, int c)
{
this.size_R = r;
this.size_C = c;
}
}
public class C_Matrix_entries
{
private S_Matrix_size _size;
public C_Matrix_entries()
{
int r, c;
Console.WriteLine("Enter number of rows and columns ");
r = Convert.ToInt32(Console.ReadLine());
c = Convert.ToInt32(Console.ReadLine());
_size = new S_Matrix_size(r,c);
double[,] entry = new double [_size.size_R,_size.size_C];
Console.WriteLine("Enter the entries from first row [left to right] to the last row ");
for (int i = 0; i<_size.size_R; i++)
{
Console.WriteLine("Enter the {0} row", i + 1);
for (int j = 0; j<_size.size_C;j++)
{
entry[i, j] = Convert.ToDouble(Console.ReadLine());
}
}
}
public S_Matrix_size Size { get { return _size; } }
}
}
namespace Row_Reduce_Algebra
{
using Matrix_Algebra;
public class TEST
{
static void Main()
{
C_Matrix_entries matrix_no1 = new C_Matrix_entries();
for (int i = 0; i < matrix_no1.Size.size_R * matrix_no1.Size.size_C; i++)
{
// TODO: something useful
Console.WriteLine(i); // FORNOW
}
}
}
}

Comparing user input to previously entered values

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.

Categories

Resources